Embed Assets
Bundle templates and static files into a single binary with go:embed.
package main
import (
"embed"
"html/template"
"log"
"net/http"
)
//go:embed templates/*.html
var templateFS embed.FS
//go:embed static/*
var staticFS embed.FS
var tmpl = template.Must(template.ParseFS(templateFS, "templates/*.html"))
func homePage(w http.ResponseWriter, r *http.Request) {
data := struct {
Title string
Items []string
}{
Title: "Bookmarks",
Items: []string{"https://go.dev", "https://pkg.go.dev"},
}
tmpl.ExecuteTemplate(w, "layout.html", data)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", homePage)
mux.Handle("GET /static/", http.FileServerFS(staticFS))
log.Println("listening on :8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}Create templates/layout.html and static/style.css next to main.go. Everything gets compiled into the binary. No files to deploy.