From 9349cda5f6d502832792a3a135abd52659af5f31 Mon Sep 17 00:00:00 2001 From: jordi fita mas Date: Sat, 5 Aug 2023 02:08:32 +0200 Subject: [PATCH] Take into account the confidence of language.Matcher MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- pkg/locale/locale.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/pkg/locale/locale.go b/pkg/locale/locale.go index ee460f4..76f0352 100644 --- a/pkg/locale/locale.go +++ b/pkg/locale/locale.go @@ -68,12 +68,14 @@ func Match(acceptLanguage string, locales Locales, matcher language.Matcher) *Lo return nil } var locale *Locale - tag, _, _ := matcher.Match(t...) - var ok bool - locale, ok = locales[tag] - for !ok && !tag.IsRoot() { - tag = tag.Parent() + tag, _, confidence := matcher.Match(t...) + if confidence > language.No { + var ok bool locale, ok = locales[tag] + for !ok && !tag.IsRoot() { + tag = tag.Parent() + locale, ok = locales[tag] + } } return locale }