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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
