i18n: subdomain code: set from cookie if settings allow it, so multiple subdomain redirections can set the language correctly instead of falling back to the default one

This commit is contained in:
Gerasimos (Makis) Maropoulos 2020-08-16 18:37:00 +03:00
parent 177b05b674
commit f8ac760f69
No known key found for this signature in database
GPG Key ID: 5DBE766BD26A54E7
2 changed files with 19 additions and 3 deletions

View File

@ -405,6 +405,22 @@ func (i *I18n) GetMessage(ctx *context.Context, format string, args ...interface
return ""
}
func (i *I18n) setLangWithoutContext(w http.ResponseWriter, r *http.Request, lang string) {
if i.Cookie != "" {
http.SetCookie(w, &http.Cookie{
Name: i.Cookie,
Value: lang,
// allow subdomain sharing.
Domain: context.GetDomain(context.GetHost(r)),
SameSite: http.SameSiteLaxMode,
})
} else if i.URLParameter != "" {
r.URL.Query().Set(i.URLParameter, lang)
}
r.Header.Set(acceptLanguageHeaderKey, lang)
}
// Wrapper returns a new router wrapper.
// The result function can be passed on `Application.WrapRouter/AddRouterWrapper`.
// It compares the path prefix for translated language and
@ -437,7 +453,7 @@ func (i *I18n) Wrapper() router.WrapperFunc {
r.RequestURI = path
r.URL.Path = path
r.Header.Set(acceptLanguageHeaderKey, lang)
i.setLangWithoutContext(w, r, lang)
found = true
}
}
@ -450,7 +466,7 @@ func (i *I18n) Wrapper() router.WrapperFunc {
host = host[dotIdx+1:]
r.URL.Host = host
r.Host = host
r.Header.Set(acceptLanguageHeaderKey, tag.String())
i.setLangWithoutContext(w, r, tag.String())
}
}
}

View File

@ -531,7 +531,7 @@ func (app *Application) Build() error {
if app.I18n.Loaded() {
// {{ tr "lang" "key" arg1 arg2 }}
app.view.AddFunc("tr", app.I18n.Tr)
app.Router.AddRouterWrapper(app.I18n.Wrapper())
app.Router.PrependRouterWrapper(app.I18n.Wrapper())
}
if n := app.view.Len(); n > 0 {