From 351c15d28e0444fd8a78c510a0c4d62ed433c758 Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Wed, 7 Aug 2024 00:21:12 +0200 Subject: Genesis commit --- main.go | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 main.go (limited to 'main.go') diff --git a/main.go b/main.go new file mode 100644 index 0000000..0624665 --- /dev/null +++ b/main.go @@ -0,0 +1,71 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "math" + "net/http" + "strconv" + "strings" + + "git.thomasvoss.com/euro-cash.eu/i18n" + "git.thomasvoss.com/euro-cash.eu/middleware" + "git.thomasvoss.com/euro-cash.eu/templates" + "github.com/a-h/templ" +) + +var components = map[string]templ.Component{ + "/": templates.Index(), + "/language": templates.SetLanguage(), +} + +func main() { + i18n.InitPrinters() + + port := flag.Int("port", 8080, "port number") + flag.Parse() + + mux := http.NewServeMux() + mux.Handle("GET /style.css", http.FileServer(http.Dir("static"))) + mux.Handle("GET /", middleware.I18n(http.HandlerFunc(finalHandler))) + mux.Handle("POST /language", http.HandlerFunc(setUserLanguage)) + + portStr := ":" + strconv.Itoa(*port) + log.Println("Listening on", portStr) + log.Fatal(http.ListenAndServe(portStr, mux)) +} + +func finalHandler(w http.ResponseWriter, r *http.Request) { + p := r.Context().Value(middleware.PrinterKey).(i18n.Printer) + ctx := context.WithValue(context.Background(), templates.PrinterKey, p) + + path := r.URL.Path + if path != "/" && path[len(path)-1] == '/' { + path = path[:len(path)-1] + } + + if c, ok := components[path]; !ok { + w.WriteHeader(http.StatusNotFound) + fmt.Fprintln(w, p.T("Page not found")) + } else { + w.WriteHeader(http.StatusOK) + templates.Root(nil, c).Render(ctx, w) + } +} + +func setUserLanguage(w http.ResponseWriter, r *http.Request) { + loc := r.FormValue(templates.LocaleKey) + _, ok := i18n.Printers[strings.ToLower(loc)] + if !ok { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "Locale ā€˜%sā€™ is invalid or unsupported", loc) + return + } + http.SetCookie(w, &http.Cookie{ + Name: "lang", + Value: loc, + MaxAge: math.MaxInt32, + }) +} -- cgit v1.2.3