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!
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.
Source Code
https://github.com/johnpili/go-embed-httprouterConclusion
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.