Package i18n provides internationalization utilities.
-
Get package:
go get -u github.com/gowww/i18n
-
Import it in your code with dependencies:
import ( "github.com/gowww/i18n" "golang.org/x/text/language" )
Make the Locales (string to string, for each language):
locales := i18n.Locales{
language.English: {
"hello": "Hello!",
},
language.French: {
"hello": "Bonjour !",
},
}
You're ready to make a handler with these locales, the default locale and the request parsers (matching the client language) you want to use.
Inside a handler, use RequestTranslator to get the translator containing the best locale for client.
Use Translator.T, Translator.THTML, Translator.Tn or Translator.TnHTML to retrieve the translation from a key.
i18n.RequestTranslator(r).T("hello")
So, to wrap an http.Handler, use Handle:
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
rt := i18n.RequestTranslator(r)
fmt.Fprint(w, rt.T("hello"))
})
http.ListenAndServe(":8080", i18n.Handle(mux, locales, language.English, i18n.ParseAcceptLanguage))
To wrap an http.HandlerFunc, use HandleFunc:
http.Handle("/", i18n.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
rt := i18n.RequestTranslator(r)
fmt.Fprint(w, rt.T("hello"))
}, locales, language.English, i18n.ParseAcceptLanguage))
http.ListenAndServe(":8080", nil)
- The i18n handler receives a request.
- It must solve one question: what's the best locale for the user?
- To determine this, it has one or more Parsers (the ones you provided). They have their own way to find a result.
- So the i18n handler questions each parser (in the same order you provided them) and each one gives no, one or more potential locale.
- The i18n handler takes the first locale having a certains confidence threshold, adds a translator to the request context and serves your own handler.
- Proposal: Localization support in Go
- Accept-Language used for locale setting — W3C
- Multi-regional and multilingual sites — Google
- Use hreflang for language and regional URLs — Google
- New markup for multilingual content — Google
- Crawling and indexing of locale-adaptive pages — Google
- SEO for multilingual sites: language-specific results without changing URL?
- Geotargeting based on IP address is broken