From 193385bd5deb7ecb021ee3273f89cceadbbd10ab Mon Sep 17 00:00:00 2001 From: Martin Fischer Date: Sun, 6 Apr 2025 22:12:47 +0200 Subject: fix: don't crash on template execution error --- lex-serve/main.go | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) (limited to 'lex-serve') 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()) } } -- cgit v1.2.3