Move language detection to frontend to make frontend cachable

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2021-09-26 13:54:57 +02:00
parent ec5728b1c3
commit 8bf7a72f54
No known key found for this signature in database
GPG Key ID: 0066F03ED215AD7D
2 changed files with 12 additions and 32 deletions

38
main.go
View File

@ -102,38 +102,14 @@ func handleIndex(w http.ResponseWriter, r *http.Request) {
return
}
if err = tpl.Execute(w, struct{ Vars map[string]string }{Vars: getJSVars(r)}); err != nil {
if err = tpl.Execute(w, struct {
Vars map[string]string
}{
Vars: map[string]string{
"version": version,
},
}); err != nil {
http.Error(w, errors.Wrap(err, "parsing template").Error(), http.StatusInternalServerError)
return
}
}
func getJSVars(r *http.Request) map[string]string {
cookie, _ := r.Cookie("lang")
cookieLang := ""
if cookie != nil {
cookieLang = cookie.Value
}
acceptLang := r.Header.Get("Accept-Language")
defaultLang := "en" // known valid language
vars := map[string]string{
"version": version,
}
switch {
case cookieLang != "":
vars["locale"] = normalizeLang(cookieLang)
case acceptLang != "":
vars["locale"] = normalizeLang(strings.Split(acceptLang, ",")[0])
default:
vars["locale"] = defaultLang
}
return vars
}
func normalizeLang(lang string) string {
return strings.ToLower(strings.Split(lang, "-")[0])
}

View File

@ -13,8 +13,12 @@ import messages from './langs/langs.js'
Vue.use(BootstrapVue)
Vue.use(VueI18n)
const cookieSet = Object.fromEntries(document.cookie.split('; ')
.map(el => el.split('=')
.map(el => decodeURIComponent(el))))
const i18n = new VueI18n({
locale,
locale: cookieSet.lang?.split(/[_-]/)[0] || navigator?.language?.split(/[_-]/)[0] || 'en',
fallbackLocale: 'en',
messages,
})