diff options
author | Martin Fischer <martin@push-f.com> | 2025-04-13 11:04:50 +0200 |
---|---|---|
committer | Martin Fischer <martin@push-f.com> | 2025-04-13 14:34:31 +0200 |
commit | 30da18147923837c0786436b7363210df80fd055 (patch) | |
tree | 3b04d0deba0a45380ecb57b90f063934dd314bef | |
parent | 48f5867c09a8e30a7d8aca471af6663fc32fcbd7 (diff) |
refactor: introduce handler struct
-rw-r--r-- | lexsurf.go | 29 |
1 files changed, 16 insertions, 13 deletions
@@ -10,12 +10,10 @@ import ( "text/template" ) -var countries = map[string]country{} -var lawsByCC = map[string]map[string]law{} - func main() { + var handler = handler{lawsByCC: map[string]map[string]law{}} text, _ := ioutil.ReadFile("countries.json") - err := json.Unmarshal(text, &countries) + err := json.Unmarshal(text, &handler.countries) if err != nil { log.Fatal("search.json", err) } @@ -35,14 +33,14 @@ func main() { log.Fatal(file.Name(), err) } cc := strings.SplitN(file.Name(), ".", 2)[0] - lawsByCC[cc] = map[string]law{} + handler.lawsByCC[cc] = map[string]law{} for _, law := range laws { if law.Redir != "" { - lawsByCC[cc][law.Redir] = law + handler.lawsByCC[cc][law.Redir] = law } } } - http.HandleFunc("/", handler) + http.HandleFunc("/", handler.handle) println("listening on 8000") log.Fatal(http.ListenAndServe(":8000", nil)) } @@ -51,7 +49,12 @@ var tpl, _ = template.New("").Funcs(template.FuncMap{ "ToUpper": strings.ToUpper, }).ParseGlob("views/*") -func handler(w http.ResponseWriter, r *http.Request) { +type handler struct { + 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.URL.Path != "/" { w.WriteHeader(http.StatusNotFound) @@ -59,7 +62,7 @@ func handler(w http.ResponseWriter, r *http.Request) { return } err := tpl.ExecuteTemplate(w, "index.html", map[string]any{ - "Countries": countries, + "Countries": h.countries, "Domain": r.Host, }) if err != nil { @@ -77,7 +80,7 @@ func handler(w http.ResponseWriter, r *http.Request) { host := parts[1] key := strings.TrimLeft(r.URL.Path, "/") if len(key) > 0 { - val, ok := lawsByCC[cc][key] + val, ok := h.lawsByCC[cc][key] if !ok { w.WriteHeader(http.StatusNotFound) w.Write([]byte("unknown law")) @@ -87,7 +90,7 @@ func handler(w http.ResponseWriter, r *http.Request) { } else { query := r.URL.Query().Get("q") if query != "" { - country, ok := countries[cc] + country, ok := h.countries[cc] if !ok { w.WriteHeader(http.StatusNotFound) w.Write([]byte("search not implemented for this country")) @@ -100,11 +103,11 @@ func handler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) } } - _, hasJSONLaws := lawsByCC[cc] + _, hasJSONLaws := h.lawsByCC[cc] err := tpl.ExecuteTemplate(w, "search.html", map[string]any{ "TLD": cc, "Domain": host, - "Country": countries[cc], + "Country": h.countries[cc], "HasJSONLaws": hasJSONLaws, }) if err != nil { |