From d218bee6b8ab4fd10bec88269270a2412bdbbb46 Mon Sep 17 00:00:00 2001 From: Martin Fischer Date: Sun, 6 Apr 2025 14:56:19 +0200 Subject: refactor: make domain configurable --- lexsurf.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) (limited to 'lexsurf.go') diff --git a/lexsurf.go b/lexsurf.go index 9ac8feb..5c1e15a 100644 --- a/lexsurf.go +++ b/lexsurf.go @@ -6,12 +6,18 @@ import ( "log" "net/http" "net/url" + "os" "strings" "text/template" ) func main() { - var handler = handler{lawsByCC: map[string]map[string]law{}} + domain := os.Getenv("DOMAIN") + if domain == "" { + log.Fatal("DOMAIN environment variable must be set") + } + + var handler = handler{domain: domain, lawsByCC: map[string]map[string]law{}} text, _ := ioutil.ReadFile("countries.json") err := json.Unmarshal(text, &handler.countries) if err != nil { @@ -50,12 +56,13 @@ var tpl, _ = template.New("").Funcs(template.FuncMap{ }).ParseGlob("views/*") type handler struct { + domain string countries map[string]country lawsByCC map[string]map[string]law } func (h *handler) handle(w http.ResponseWriter, r *http.Request) { - if r.Host == "lex.surf" || r.Host == "lex.localhost" { + if r.Host == h.domain { if r.URL.Path != "/" { w.WriteHeader(http.StatusNotFound) w.Write([]byte("page not found")) @@ -71,13 +78,11 @@ func (h *handler) handle(w http.ResponseWriter, r *http.Request) { return } - parts := strings.SplitN(r.Host, ".", 2) - if len(parts) != 2 { + cc, isSubdomain := strings.CutSuffix(r.Host, "."+h.domain) + if !isSubdomain { w.Write([]byte("unknown host")) return } - cc := parts[0] - host := parts[1] key := strings.TrimLeft(r.URL.Path, "/") if len(key) > 0 { val, ok := h.lawsByCC[cc][key] @@ -106,7 +111,7 @@ func (h *handler) handle(w http.ResponseWriter, r *http.Request) { _, hasJSONLaws := h.lawsByCC[cc] err := tpl.ExecuteTemplate(w, "search.html", map[string]any{ "TLD": cc, - "Domain": host, + "Domain": h.domain, "Country": h.countries[cc], "HasJSONLaws": hasJSONLaws, }) -- cgit v1.2.3