Golang : Embedded or data bundling example

Golang complies your source code into a single executable file that allows your program end users to deploy the executable at target machine with ease. However, there are times when the executable needs to load external resources such as images or HTML templates to function properly (such as showing a splash screen) and this can make the downloading process cumbersome for your end users.

Other motivations could be that you want to optimize your Golang program execution time and do not want to slow down by loading external resource or you do not want your end users to modify the images or HTML templates that your program depends on.

There are couple of ways to put everything(embed/bundle) into a single executable file instead of having multiple files. Depending on your resources, the technique to handle text data for example, can be done with this method :

 textData = `this is an example of bundling 
 text data in your program executable`

to print, use fmt.Println(textData)

As for bundling image, convert the image into base64 string ( see full example at encode image to base64 tutorial )

 imgFile, err := os.Open("QrImgGA.png") // a QR code image
 // convert the buffer bytes to base64 string - use buf.Bytes() for new image
 imgBase64Str := base64.StdEncoding.EncodeToString(buf)

then you can store the imgBase64Str string directly inside your source code and decode it back during runtime for display

 imgFile, err := base64.StdEncoding.DecodeString(imgBase64Str) 

or if your program is displaying the base64 encoded image directly to browser, then do this instead :

 // Embed into an html without PNG file
 img2html := "<html><body><img src=\"data:image/png;base64," + imgBase64Str + "\" /></body></html>"

Another option that you might want to explore is to use the go-bindata command line tool :


Go-bindata converts any static file into a byte slice that can be embedded in your code.


Bear in mind that by bundling/embedding resource data into your executable might cause it to become large and also hard to debug/maintain in future by other people. Back in my old tech support days, I have to request help from the development team to look at the source code (written in C) for a very strange error message caused by bundled resource. Not an easy task if the original developer left the organisation long time ago and there's no written document on which resources are embedded in the executable.

References :




  See also : Golang : How to protect your source code from client, hosting company or hacker?

By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.