From 8bf7a72f5480c590bc8735029f3fd8fffc6d2119 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sun, 26 Sep 2021 13:54:57 +0200 Subject: [PATCH] Move language detection to frontend to make frontend cachable Signed-off-by: Knut Ahlers --- main.go | 38 +++++++------------------------------- src/main.js | 6 +++++- 2 files changed, 12 insertions(+), 32 deletions(-) diff --git a/main.go b/main.go index 2a968db..237813c 100644 --- a/main.go +++ b/main.go @@ -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]) -} diff --git a/src/main.js b/src/main.js index 0d6fd87..8392396 100644 --- a/src/main.js +++ b/src/main.js @@ -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, })