Skip to content

Commit 1426601

Browse files
authored
Use index of the supported tags to choose user lang (#15452)
Fix #14793. The previous implementation used the first return value of matcher.Match, which is the chosen language tag but may contain extensions such as de-DE-u-rg-chzzzz. As mentioned in the documentation of language package, matcher.Match also returns the index of the supported tags, so I think it is better to use it rather than manipulate the returned language tag.
1 parent 078df7a commit 1426601

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

modules/translation/translation.go

+9-7
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,9 @@ type LangType struct {
2525
}
2626

2727
var (
28-
matcher language.Matcher
29-
allLangs []LangType
28+
matcher language.Matcher
29+
allLangs []LangType
30+
supportedTags []language.Tag
3031
)
3132

3233
// AllLangs returns all supported langauages
@@ -50,12 +51,12 @@ func InitLocales() {
5051
}
5152
}
5253

53-
tags := make([]language.Tag, len(setting.Langs))
54+
supportedTags = make([]language.Tag, len(setting.Langs))
5455
for i, lang := range setting.Langs {
55-
tags[i] = language.Raw.Make(lang)
56+
supportedTags[i] = language.Raw.Make(lang)
5657
}
5758

58-
matcher = language.NewMatcher(tags)
59+
matcher = language.NewMatcher(supportedTags)
5960
for i := range setting.Names {
6061
key := "locale_" + setting.Langs[i] + ".ini"
6162
if err = i18n.SetMessageWithDesc(setting.Langs[i], setting.Names[i], localFiles[key]); err != nil {
@@ -73,8 +74,9 @@ func InitLocales() {
7374
}
7475

7576
// Match matches accept languages
76-
func Match(tags ...language.Tag) (tag language.Tag, index int, c language.Confidence) {
77-
return matcher.Match(tags...)
77+
func Match(tags ...language.Tag) language.Tag {
78+
_, i, _ := matcher.Match(tags...)
79+
return supportedTags[i]
7880
}
7981

8082
// locale represents the information of localization.

modules/web/middleware/locale.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale {
3838
// The first element in the list is chosen to be the default language automatically.
3939
if len(lang) == 0 {
4040
tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language"))
41-
tag, _, _ := translation.Match(tags...)
41+
tag := translation.Match(tags...)
4242
lang = tag.String()
4343
}
4444

0 commit comments

Comments
 (0)