package main import ( "embed" "flag" "fmt" "html/template" "io/fs" "log" "net/http" ) //go:embed source var sourceFS embed.FS func main() { port := flag.Int("port", 8081, "port to listen on") flag.Parse() sourceRoot, err := fs.Sub(sourceFS, "source") if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.HandleFunc("GET /{$}", servePage("home", "templates/pages/index.html", sourceRoot, false)) mux.HandleFunc("GET /research", servePage("research", "templates/pages/research.html", sourceRoot, true)) mux.HandleFunc("GET /bookkeeping", servePage("bookkeeping", "templates/pages/bookkeeping.html", sourceRoot, true)) mux.HandleFunc("GET /personal", servePage("personal", "templates/pages/interests.html", sourceRoot, true)) staticRoot, err := fs.Sub(sourceFS, "source/static") if err != nil { log.Fatal(err) } mux.Handle("/static/", http.StripPrefix("/static/", http.FileServerFS(staticRoot))) mux.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { http.ServeFileFS(w, r, sourceRoot, "favicon.ico") }) addr := fmt.Sprintf(":%d", *port) log.Printf("running on http://localhost%s/\n", addr) log.Fatal(http.ListenAndServe(addr, mux)) } func servePage(name string, templatefile string, sourcefile fs.FS, sub bool) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { tmpl, err := template.ParseFS(sourcefile, "templates/main.html", templatefile) if err != nil { log.Println("parse error:", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } data := struct { Title string Sub bool }{ Title: name, Sub: sub, } w.Header().Set("Content-Type", "text/html; charset=utf-8") // execute the base file by name — main.html is the entrypoint if err := tmpl.ExecuteTemplate(w, "main.html", data); err != nil { log.Println("execute error:", err) http.Error(w, err.Error(), http.StatusInternalServerError) } } }