Reputation: 350
I'm working on a website which needs to deliver web pages in different languages as selected by the user. e.g. if the user selects Spanish as his preferred language, the server should send text elements of web pages in Spanish.
What is the standard way of doing it in Go? I'd also love to know what methods you guys are using.
Thanks.
Upvotes: 6
Views: 2024
Reputation: 4714
If a user's preferred language has a possibility of being unavailable, you can use Golang's text/language package to match requested languages to supported languages.
This type of language matching is a non-trivial problem as outlined in this excellent post in The Go Blog.
To use the language package, create a matcher with a slice of supported languages:
var serverLangs = []language.Tag{
language.AmericanEnglish, // en-US fallback
language.German, // de
}
var matcher = language.NewMatcher(serverLangs)
Then match against one or more preferred languages. (The preferred language may be based on the user's IP address or the Accept-Language
header.)
var userPrefs = []language.Tag{
language.Make("gsw"), // Swiss German
language.Make("fr"), // French
}
tag, index, confidence := matcher.Match(sortLanguageTags(&langs, DescendingQuality)...)
To retrieve the corresponding text for the language, you can use the tag.String()
method:
type Translation map[string]string
type Translations map[string]Translation
translations := Translations{
"knee": {
language.German.String(): "knie",
language.AmericanEnglish.String(): "knee",
},
}
fmt.Println(translations["knee"][tag.String()]) // prints "knie"
Upvotes: 5
Reputation: 192
I allways use a map and define a function on it, which returns the text for a given key:
type Texts map[string]string
func (t *Texts) Get(key string) string{
return (*t)[key]
}
var texts = map[string]Texts{
"de":Texts{
"title":"Deutscher Titel",
},
"en":Texts{
"title":"English title",
},
}
func executeTemplate(lang string){
tmpl, _ := template.New("example").Parse(`Title: {{.Texts.Get "title" }} `)
tmpl.Execute(os.Stdout,struct{
Texts Texts
}{
Texts: texts[lang],
})
}
Upvotes: 7