diff options
author | Thomas Voss <mail@thomasvoss.com> | 2024-08-07 00:21:12 +0200 |
---|---|---|
committer | Thomas Voss <mail@thomasvoss.com> | 2024-08-07 00:21:12 +0200 |
commit | 351c15d28e0444fd8a78c510a0c4d62ed433c758 (patch) | |
tree | b97aae6ec45c1b341075da147fb9e333246c19f7 /main.go |
Genesis commit
Diffstat (limited to 'main.go')
-rw-r--r-- | main.go | 71 |
1 files changed, 71 insertions, 0 deletions
@@ -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, + }) +} |