The go:embed feature was introduce in Go 1.16. It lets you embed resources into the compiled application. Prior to version 1.16, developers uses external tooling to do this. With go:embed you can embed images, webpages, email templates, predefined SQL statements or an entire directory. That’s neat!

imagen

Usage Examples

Embedding a text file in a string

//go:embed version.txt
var version string

Embedding a binary file

//go:embed product-catalog.pdf
var catalog []byte

Embedding a directory filesystem

//go:embed template/*
var templateFS fs.FS

Embedded resources in httprouter

Project Structure

go-embed-httprouter
 ├─static/
 │  └─img/
 │     ├─cat1.jpg
 │     ├─cat2.jpg
 │     └─cat3.jpg
 └─main.go  

main.go

package main

import (
	"embed"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"io/fs"
	"log"
	"net/http"
	"time"
)

//go:embed static/*
var staticFS embed.FS

func main() {
	f := fs.FS(staticFS)
	v, _ := fs.Sub(f, "static")

	router := httprouter.New()
	router.ServeFiles(fmt.Sprintf("%s", "/static/*filepath"), http.FS(v))
	router.HandlerFunc(http.MethodGet, "/", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/static/img/cat1.jpg", http.StatusTemporaryRedirect)
	})

	port := "8080"
	httpServer := &http.Server{
		Addr:         ":" + port,
		Handler:      router,
		ReadTimeout:  120 * time.Second,
		WriteTimeout: 120 * time.Second,
	}

	log.Printf("Server running at http://localhost:%s/\n", port)
	log.Fatal(httpServer.ListenAndServe())
}

Verifying the embedded files

One way to verify for the embedded files inside the compiled application is by a hex editor. Using the hex editor, find the marker for the JPEG File Interchange Format (JFIF). In this case, we will look for 3 jpeg images.

1st jpeg at Offset: 002A:E7CA imagen

2nd jpeg at Offset: 002C:A6EA imagen

3rd jpeg at Offset: 002F:06EA imagen

Source Code

https://github.com/johnpili/go-embed-httprouter

Conclusion

The ability to embed all resources inside the compiled binary application is a powerful feature. It makes the application portable and easier to deploy. With go:embed, you don’t need an installer or script to unpack and use your resources.

Resources

https://www.w3.org/Graphics/JPEG/jfif3.pdf

https://pkg.go.dev/embed