1
0

Set lang if a lang= query set, else look for a cookie, otherwise choose a lang from Accept-Language header.

This commit is contained in:
Alexander Andreev 2024-09-15 00:31:00 +04:00
parent d26bcc58b8
commit 802c925450
Signed by: Arav
GPG Key ID: 25969B23DCB5CA34

View File

@ -126,7 +126,19 @@ func main() {
func I18nMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, err := ctxi18n.WithLocale(r.Context(), r.Header.Get("Accept-Language"))
lang := "en"
if lq := r.URL.Query().Get("lang"); lq != "" {
lc := http.Cookie{Name: "lang", Value: lq, HttpOnly: true, MaxAge: 0}
http.SetCookie(w, &lc)
lang = lq
} else if l, err := r.Cookie("lang"); err == nil {
lang = l.Value
} else if al := r.Header.Get("Accept-Language"); al != "" {
lang = r.Header.Get("Accept-Language")
}
ctx, err := ctxi18n.WithLocale(r.Context(), lang)
if err != nil {
log.Println("i18nmw:", err)
}