diff options
author | Martin Fischer <martin@push-f.com> | 2025-04-06 22:12:47 +0200 |
---|---|---|
committer | Martin Fischer <martin@push-f.com> | 2025-04-13 23:18:01 +0200 |
commit | 193385bd5deb7ecb021ee3273f89cceadbbd10ab (patch) | |
tree | 11dda7bbf74d4ddd3186707e5e05b3b60268a83f | |
parent | 281d0a867bc542bef52d5091fed3bf1b0d3b9ef6 (diff) |
fix: don't crash on template execution error
-rw-r--r-- | lex-serve/main.go | 19 |
1 files changed, 14 insertions, 5 deletions
diff --git a/lex-serve/main.go b/lex-serve/main.go index 826548f..f06d1a1 100644 --- a/lex-serve/main.go +++ b/lex-serve/main.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "embed" "encoding/json" "io/ioutil" @@ -72,7 +73,7 @@ var templates embed.FS var tpl, _ = template.New("").Funcs(template.FuncMap{ "ToUpper": strings.ToUpper, -}).ParseFS(templates, "templates/*") +}).Option("missingkey=error").ParseFS(templates, "templates/*") type handler struct { domain string @@ -87,13 +88,17 @@ func (h *handler) handle(w http.ResponseWriter, r *http.Request) { w.Write([]byte("page not found")) return } - err := tpl.ExecuteTemplate(w, "index.html.tmpl", map[string]any{ + var html bytes.Buffer + err := tpl.ExecuteTemplate(&html, "index.html.tmpl", map[string]any{ "Countries": h.countries, "Domain": r.Host, }) if err != nil { - log.Fatal(err) + log.Printf("failed to execute index template: %s", err) + http.Error(w, "internal server error", http.StatusInternalServerError) + return } + w.Write(html.Bytes()) return } @@ -128,15 +133,19 @@ func (h *handler) handle(w http.ResponseWriter, r *http.Request) { } } _, hasJSONLaws := h.lawsByCC[cc] - err := tpl.ExecuteTemplate(w, "search.html.tmpl", map[string]any{ + var html bytes.Buffer + err := tpl.ExecuteTemplate(&html, "search.html.tmpl", map[string]any{ "TLD": cc, "Domain": h.domain, "Country": h.countries[cc], "HasJSONLaws": hasJSONLaws, }) if err != nil { - log.Fatal(err) + log.Printf("failed to execute search template: %s", err) + http.Error(w, "internal server error", http.StatusInternalServerError) + return } + w.Write(html.Bytes()) } } |