From f8ac760f69de8905c6ff57527baf46e06dad67a4 Mon Sep 17 00:00:00 2001 From: "Gerasimos (Makis) Maropoulos" Date: Sun, 16 Aug 2020 18:37:00 +0300 Subject: [PATCH] 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 --- i18n/i18n.go | 20 ++++++++++++++++++-- iris.go | 2 +- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/i18n/i18n.go b/i18n/i18n.go index 945e822d..dde5d76b 100644 --- a/i18n/i18n.go +++ b/i18n/i18n.go @@ -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()) } } } diff --git a/iris.go b/iris.go index e16a3c2a..f86555d5 100644 --- a/iris.go +++ b/iris.go @@ -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 {