Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you embed static files into a Go binary using go:embed?
//go:embed (Go 1.16) embeds files and directories into the compiled binary at build time. This eliminates the need to distribute static assets separately — the binary is fully self-contained.
import "embed" // Embed a single file as a string //go:embed VERSION var version string // Embed a single file as bytes //go:embed config/default.yaml var defaultConfig []byte // Embed multiple files as an FS //go:embed static/* var staticFiles embed.FS // Embed entire directory tree (include hidden files with all:) //go:embed all:templates var templates embed.FS // Serving embedded static files func main() { // Serve from embedded FS staticFS, err := fs.Sub(staticFiles, "static") if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS)))) // HTML template from embedded FS tmpl := template.Must( template.New("").ParseFS(templates, "templates/*.html")) mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { tmpl.ExecuteTemplate(w, "index.html", map[string]any{ "Version": version, }) }) http.ListenAndServe(":8080", mux) } // embed.FS implements fs.FS â compatible with all fs.FS consumers
More Related questions...