I'm having the following piece of code in go:
var languageMatcher = language.NewMatcher([]language.Tag{
language.English, // Default if no match
language.French,
})
lang, _ := r.Cookie("lang")
accept := r.Header.Get("Accept-Language")
var cookieValue = ""
if cookie != nil {
cookieValue = lang.String()
}
tag, _ := language.MatchStrings(languageMatcher, cookieValue, accept)
log.Debugf(ctx, fmt.Sprintf("Localized %s to %s. cookie: %s | header: %s", path, tag.String(), cookieValue, accept))
http.Redirect(w, r, "/"+tag.String()+path, 302)
Most of it comes from the GoDoc
It's working fine most of the time but sometimes (when browsing in private mode from a computer that never visited the website, or when removing the entire cache from the browser (no lang cookie)); the language.MatchStrings
function returns a bunch of garbage in the tag variable like en-u-rg-uszzzz
.
Here's the my log.Debugf output:
Localized / to en-u-rg-uszzzz. cookie: | header: en-US,en;q=0.9
Any idea of what is wrong ?
According to the documentation, the language matcher may add the Unicode extension on the tag:
The index returned by the Match method corresponds to the index of the matched tag in t, but is augmented with the Unicode extension ('u')of the corresponding preferred tag. This allows user locale options to be passed transparently.
This explains the weird en-u-rg-uszzzz
value. As the matcher provides us the index of the matched language in the array, a workaround would be to use it to retrieve the original language:
var availableLanguages = []language.Tag{
language.English, // Default if no match
language.French,
}
var languageMatcher = language.NewMatcher(availableLanguages)
lang, _ := r.Cookie("lang")
accept := r.Header.Get("Accept-Language")
var cookieValue = ""
if lang != nil { // Be careful: the variable name was wrong
cookieValue = lang.String()
}
_, i := language.MatchStrings(languageMatcher, cookieValue, accept)
log.Debugf(ctx, fmt.Sprintf("Localized %s to %s. cookie: %s | header: %s", path, availableLanguages[i].String(), cookieValue, accept))
http.Redirect(w, r, "/"+availableLanguages[i].String()+path, 302)
A bit hacky, but it works.
Regards!