Take into account the confidence of language.Matcher

I had a weird but that sometimes the application would use Spanish as
the default language, even though the user had not passed Spanish as
value of the Accept-Language header and the default is hard-coded to
Catalan.

I learned that language.Matcher **always** returns one of its defined
locales, even if there is no way to match the passed list of languages
to Match.  In that case, it returns a confidence of “No”, meaning that
the match failed.

Usually go the default Catalan locale because most of the time this was
set as the first language to Matcher, but since Go randomizes maps,
there were times that Spanish was first.
This commit is contained in:
jordi fita mas 2023-08-05 02:08:32 +02:00
parent 1b923a9f65
commit 9349cda5f6
1 changed files with 7 additions and 5 deletions

View File

@ -68,12 +68,14 @@ func Match(acceptLanguage string, locales Locales, matcher language.Matcher) *Lo
return nil return nil
} }
var locale *Locale var locale *Locale
tag, _, _ := matcher.Match(t...) tag, _, confidence := matcher.Match(t...)
var ok bool if confidence > language.No {
locale, ok = locales[tag] var ok bool
for !ok && !tag.IsRoot() {
tag = tag.Parent()
locale, ok = locales[tag] locale, ok = locales[tag]
for !ok && !tag.IsRoot() {
tag = tag.Parent()
locale, ok = locales[tag]
}
} }
return locale return locale
} }