Skip to content

Commit 4bd1fcb

Browse files
tiqwabzeripath
authored andcommitted
Use index of the supported tags to choose user lang (go-gitea#15452)
Backport go-gitea#15452 Fix go-gitea#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 b28c324 commit 4bd1fcb

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
@@ -27,8 +27,9 @@ type LangType struct {
2727
}
2828

2929
var (
30-
matcher language.Matcher
31-
allLangs []LangType
30+
matcher language.Matcher
31+
allLangs []LangType
32+
supportedTags []language.Tag
3233
)
3334

3435
// AllLangs returns all supported langauages
@@ -51,12 +52,12 @@ func InitLocales() {
5152
}
5253
}
5354

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

59-
matcher = language.NewMatcher(tags)
60+
matcher = language.NewMatcher(supportedTags)
6061
for i := range setting.Names {
6162
key := "locale_" + setting.Langs[i] + ".ini"
6263
if err = i18n.SetMessageWithDesc(setting.Langs[i], setting.Names[i], localFiles[key]); err != nil {
@@ -79,8 +80,9 @@ func InitLocales() {
7980
}
8081

8182
// Match matches accept languages
82-
func Match(tags ...language.Tag) (tag language.Tag, index int, c language.Confidence) {
83-
return matcher.Match(tags...)
83+
func Match(tags ...language.Tag) language.Tag {
84+
_, i, _ := matcher.Match(tags...)
85+
return supportedTags[i]
8486
}
8587

8688
// 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)