-Migrated from my original blog
This post came from one of the challenges set by my local GoLang user group.
Create an API with an endpoint that returns a PNG image containing the numeric representation of the number of times that endpoint has been hit.
A data URI is basically a base64 bit encoded string of characters. You can encode many different types of data including binary data such as images. Most modern browsers can decode data URIs automatically.
A great post on the basics of data URIs in web development is CSS-Tricks Data URI. This is where I first learned about them. Reading that post you will hopefully see the nerd coolness that they are.
In reality with modern web technologies data URIs are becoming more and more impractical, because in reality they are 20% to 35% larger than their standard counterparts. You could gzip the data and for Go Lang there is a really good package from the New York Times: gziphandler.
With that excessive size does come with a bonus. With typical HTTP requests for files such ad HTML, or images require an additional request to retrieve that file. That could be “OK” for mobile, or some sort of restricted device.
With a data URI, it can be sent over the request body as a simple string. Once the browser receives the string it will see a prefix:
Source: MDN Data URI; NOTE: The MDN site is one of the best resources for learning client-side web technologies out there. It is VERY thorough.
As you can see from the Mozilla Developer Network Article you can encode many types of data for the browser.
- Plain Text
And while dealing with
text data types you don’t even need to encode it, but
binary types, like images, they will need to be encoded.
GETTING TO THE CODE
With this tutorial we will just focus on creating the data URI string to be sent. At that point you can send it over some sort of API, or embedded in an HTML template. Also we will only use packages from the
To simplify things I am going to borrow most of the code for generating images from another one of my favorite sources SocketLoop. SocketLoop always seems to have the answers for any golang question I have. Specifically we will be using this blog post, a great resource on how to create images in golang.
Here are the imports:
You may be asking why the
time packages. That’s because per the Socket Loop Tutorial we will be generating a randomly generated simple QR-Code like PNG image.
Let’s get to the main
Ok well we now have generated the image in memory now lets get to the fun stuff.
First we need to create a bytes buffer that we can write into and read out to encode into a PNG from the image we created. Then we will take that buffer as a byte slice and output it as a string.
Nerd cool right?
Again without gzipping it typically is larger than its binary counterpart, but does reduce HTTP requests.
Check out the full source code on GitHub