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 /middleware |
Genesis commit
Diffstat (limited to 'middleware')
-rw-r--r-- | middleware/i18n.go | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/middleware/i18n.go b/middleware/i18n.go new file mode 100644 index 0000000..5e33636 --- /dev/null +++ b/middleware/i18n.go @@ -0,0 +1,41 @@ +package middleware + +import ( + "cmp" + "context" + "errors" + "log" + "net/http" + "strings" + + "git.thomasvoss.com/euro-cash.eu/i18n" + "git.thomasvoss.com/euro-cash.eu/templates" +) + +const PrinterKey = "printer" + +func I18n(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var p, pZero i18n.Printer + + if c, err := r.Cookie("lang"); errors.Is(err, http.ErrNoCookie) { + log.Println("Language cookie not set") + } else { + var ok bool + p, ok = i18n.Printers[strings.ToLower(c.Value)] + if !ok { + log.Printf("Language ā%sā is unsupported\n", c.Value) + } + } + + used := cmp.Or(p, i18n.DefaultPrinter) + ctx := context.WithValue(r.Context(), PrinterKey, used) + + if p == pZero { + templates.Root(nil, templates.SetLanguage()).Render(ctx, w) + /* TODO: Redirect the user back to where they came from */ + } else { + next.ServeHTTP(w, r.WithContext(ctx)) + } + }) +} |