// SPDX-License-Identifier: AGPL-3.0-or-later package httpapi import ( "context" "net/http" "time" "docwell/server/internal/auth" "docwell/server/internal/i18n" ) // Languages: the apps send the language they show in Accept-Language. Each // response says its language in Content-Language, error messages are // translated into it (writeError), and the request's context carries it for // text written while handling it (invite emails). A signed-in person's last // language is stored for the emails and notifications they get later. // withLang sets a request's language on its context and response. func withLang(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { lang := i18n.Match(r.Header.Get("Accept-Language")) w.Header().Set("Content-Language", lang) next.ServeHTTP(w, r.WithContext(i18n.WithLang(r.Context(), lang))) }) } // responseLang is the language withLang chose for a response. func responseLang(w http.ResponseWriter) string { if l := w.Header().Get("Content-Language"); i18n.IsSupported(l) { return l } return i18n.Default } // rememberLocale stores the language a signed-in person uses when it // changed (in the background; once per user and language per process). func (a *api) rememberLocale(r *http.Request, u auth.User) { lang, ok := i18n.MatchOK(r.Header.Get("Accept-Language")) if !ok || u.ID == "" || lang == u.Locale { return } if prev, seen := a.locales.Load(u.ID); seen && prev == lang { return } a.locales.Store(u.ID, lang) go func() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := a.auth.SetLocale(ctx, u.ID, lang); err != nil { a.locales.Delete(u.ID) a.log.Warn("remember locale", "user", u.ID, "err", err) } }() }