Go Embed instead of Packr

Sudaraka Jayathilaka
2 min readDec 5, 2021

--

image : https://claudemuller.io/
image : https://claudemuller.io/

Many of the microservices I am working on right now are written in Golang. Most of these microservices have internal dashboards and the UI tends to be served from the respective microservices. For serving a UI from a Golang service (or any other service), you need to serve the UI files from the service. But especially in Golang, this used to be not very straightforward. Although we can serve files from a certain folder using a static file server feature in Golang, the language was missing the native support to bundle UI files with the service executable. For getting this done, there are several open-source Golang libraries out there such as

We were using the packer library from above. On the high level, these libraries serialized all the static content and stored the serialized contents inside .go files. So once we update any of the static contents, we had to run a specific command for the serialization and generating the new .go files.

But then on one bright sunny day, the Golang team introduced their latest feature, Embedded Files in their latest version go 1.16. Since this native way of embedding files eliminates the need of generating files explicitly and it looks more convenient, we wanted to make the switch in our services.

I faced with few challenges while doing the switch,

  1. Go embed directive doesn’t support paths with .. according to the documentation (accessing the parent file)
  2. Go embed always considers the path from the root. eg: if the file is project-root/static/index.html you will be able to access the file on http://localhost:8080/static/index.html

As the solution to the first problem, I ended up defining the //go:embed directive in the main.go

But as a solution to the other problem, I came up with the following implementation,

You can see a working demo in the below repo

--

--