// Chapter 47 example: a template and a stylesheet inside the program itself. // // Run from this folder: // cd exercises/47/06-embed // go run . // // Or build it, and run the .exe from any folder: // go build -o embeddemo.exe . package main import ( "bytes" "embed" "html/template" "log/slog" "net/http" "os" "time" ) // files holds the folders templates and static, read when the program is // built. The comment must sit right above the variable, with no space after //. // //go:embed templates static var files embed.FS var version = "dev" var pages *template.Template func handleHome(w http.ResponseWriter, r *http.Request) { var page bytes.Buffer err := pages.ExecuteTemplate(&page, "home.html", version) if err != nil { slog.Error("template failed", "err", err) http.Error(w, "The page could not be built.", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") page.WriteTo(w) } func main() { parsed, err := template.ParseFS(files, "templates/*.html") if err != nil { slog.Error("could not parse the templates", "err", err) os.Exit(1) } pages = parsed mux := http.NewServeMux() mux.HandleFunc("GET /{$}", handleHome) // The paths inside files start with static/, the same as the URLs. mux.Handle("GET /static/", http.FileServerFS(files)) srv := &http.Server{ Addr: "localhost:8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, } slog.Info("server starting", "addr", srv.Addr, "version", version) err = srv.ListenAndServe() slog.Error("server stopped", "err", err) os.Exit(1) }