bundle := i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
lang := []string{"en-US", "fr"}
for i := 0; i < len(lang); i++ {
bundle.LoadMessageFile(fmt.Sprintf("json/%s.json", lang[I]))
}
localizer := i18n.NewLocalizer(bundle, "en-US")
appConfig := handler.AppConfig{T: t, Localizer: localizer}
//common.ChangeString(&str)
r.Use(middlewares.I18n(bundle, &appConfig))
middleware
func I18n(bundle *i18n.Bundle, appConfig *handler.AppConfig) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
lang := r.URL.Query().Get("lang")
if lang == "" {
lang = "en-US"
url, _ := common.FullUrl(r)
fmt.Println(url)
q := url.Query()
q.Add("lang", lang)
url.RawQuery = q.Encode()
http.Redirect(w, r, url.String(), http.StatusPermanentRedirect)
}
accept := r.Header.Get("Accept-Language")
fmt.Println("accept", accept)
localizer := i18n.NewLocalizer(bundle, lang, accept)
appConfig.Localizer = localizer
appConfig.Lang = lang
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
inside some handlers...
fmt.Println(l.config.Lang) //it is empty - what is wrong here?
Hi,
may you add some description beside the code?
Which packages are you using?
where those packages come from ?
i18n => “github.com/nicksnyder/go-i18n/v2/i18n”
handler => custom package which contains the struct to hold the config
But it seems, by using middleware, it is not possible to change the value. Because everything compiled and I get the old data only. I don’t know exactly what happens.
Right now, I have created a new package to handle i18n (local package is also named as i18n. I have to think and rename it)
I have implemented the translate method for that package
func (i18 *I18n) Translate(text string) string {
fmt.Println("Translate..", i18)
localizer := i18n.NewLocalizer(i18.Bundle, i18.Lang)
str, err := localizer.Localize(&i18n.LocalizeConfig{MessageID: text})
if err != nil {
return err.Error()
}
return str
}
I pass the i18n struct to all my templates. Inside the templates, I call the function `translate
{{translate "login"}}
//translated to Login
I made it working somehow.
//if you really need the code, I can create a simple go chi middleware and share the code.like changing the value of a string. I tried that, That is also not working. (even after passing the address) Old value is printed
Hi,
wondering if a better approach would be that the middleware adds the localizer to request’s Context instead of modifying the global appConfig.
I think thos would be a better approach to avoid that multiple requests change the global appConfigg in concurrent way
1 Like
Hi,
I tried that approach. It is working good. with middleware’s context is the best solution.
Thanks a lot