From d0fd2be150fcd25ec186d639b662ea9cc351869b Mon Sep 17 00:00:00 2001 From: talksik Date: Sun, 9 Nov 2025 13:42:43 -0800 Subject: [PATCH] render html in default route --- cmd/main.go | 51 ++++++++++++++++++++++++--------------------------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index b0a8170..b94f5b8 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -1,51 +1,48 @@ package main import ( - "fmt" "html/template" "log" "net/http" - "os" ) var x = 2 -func testTemplate() { - const tpl = ` +func main() { + http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { + w.WriteHeader(200) + // fmt.Fprintf(w, "Welcome to the home page!") + const tpl = ` {{.Title}} + - {{range .Items}}
{{ . }}
{{else}}
no rows
{{end}} + {{range .Items}}
{{ . }}
{{else}}
no rows
{{end}} ` - t, err := template.New("default").Parse(tpl) - if err != nil { - log.Fatalf("%v", err) - } + t, err := template.New("default").Parse(tpl) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } - data := struct { - Title string - Items []string - }{ - Title: "Hello", - Items: []string{"yo", template.HTMLEscapeString("what's up")}, - } - err = t.Execute(os.Stdout, data) - if err != nil { - log.Fatalf("%v", err) - } - -} - -func main() { - http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(200) - fmt.Fprintf(w, "Welcome to the home page!") + data := struct { + Title string + Items []string + }{ + Title: "Hello", + Items: []string{"yo", "what's up"}, // template automatically escapes it + } + err = t.Execute(w, data) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } }) log.Printf("listening on port 8080") log.Fatal(http.ListenAndServe(":8080", nil))