// Homework 47, challenge: Ship it. // // This server reads its template from the disk, so it works only when run from // this folder, and its address is fixed. Change it so that: // - the template is embedded in the program with //go:embed // - the address comes from -addr, or HELLO_ADDR, or "localhost:8080" // - a version variable, "dev" unless set with -ldflags, is shown on the page // - -version prints "hello " and stops // Then build hello.exe with version 1.0.0, run it from go-work, and build a // Linux version too. // // Run from this folder: // cd exercises/47/homework/04-ship-it // go run . package main import ( "bytes" "fmt" "html/template" "net/http" ) var pages *template.Template func handleHome(w http.ResponseWriter, r *http.Request) { var page bytes.Buffer err := pages.ExecuteTemplate(&page, "hello.html", "TODO") if err != nil { fmt.Println("Template error:", 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() { // TODO: read the template from an embed.FS instead of the disk. parsed, err := template.ParseFiles("templates/hello.html") if err != nil { fmt.Println("Could not read the template:", err) return } pages = parsed http.HandleFunc("GET /{$}", handleHome) // TODO: take the address from the settings. fmt.Println("Server running at http://localhost:8080") err = http.ListenAndServe("localhost:8080", nil) if err != nil { fmt.Println("Server stopped:", err) } }