This is an automated email from the ASF dual-hosted git repository.

linkinstar pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/incubator-answer.git


The following commit(s) were added to refs/heads/dev by this push:
     new 0df7bec0 fix: parse user Accept-Language
0df7bec0 is described below

commit 0df7bec0c8062451572bd06f0a0848444d5a7796
Author: Luffy <[email protected]>
AuthorDate: Tue Dec 24 14:52:47 2024 +0800

    fix: parse user Accept-Language
---
 internal/base/middleware/accept_language.go | 34 +++++++++++++----------------
 1 file changed, 15 insertions(+), 19 deletions(-)

diff --git a/internal/base/middleware/accept_language.go 
b/internal/base/middleware/accept_language.go
index 6cb7d95d..3eaad75e 100644
--- a/internal/base/middleware/accept_language.go
+++ b/internal/base/middleware/accept_language.go
@@ -22,36 +22,32 @@ package middleware
 import (
        "github.com/apache/incubator-answer/internal/base/constant"
        "github.com/apache/incubator-answer/internal/base/handler"
+       "github.com/apache/incubator-answer/internal/base/translator"
        "github.com/gin-gonic/gin"
        "github.com/segmentfault/pacman/i18n"
-)
-
-var (
-       langMapping = map[i18n.Language]bool{
-               i18n.LanguageChinese:            true,
-               i18n.LanguageChineseTraditional: true,
-               i18n.LanguageEnglish:            true,
-               i18n.LanguageGerman:             true,
-               i18n.LanguageSpanish:            true,
-               i18n.LanguageFrench:             true,
-               i18n.LanguageItalian:            true,
-               i18n.LanguageJapanese:           true,
-               i18n.LanguageKorean:             true,
-               i18n.LanguagePortuguese:         true,
-               i18n.LanguageRussian:            true,
-               i18n.LanguageVietnamese:         true,
-       }
+       "golang.org/x/text/language"
+       "strings"
 )
 
 // ExtractAndSetAcceptLanguage extract accept language from header and set to 
context
 func ExtractAndSetAcceptLanguage(ctx *gin.Context) {
        // The language of our front-end configuration, like en_US
        lang := handler.GetLang(ctx)
-       if langMapping[lang] {
-               ctx.Set(constant.AcceptLanguageFlag, lang)
+       tag, _, err := language.ParseAcceptLanguage(string(lang))
+       if err != nil || len(tag) == 0 {
+               ctx.Set(constant.AcceptLanguageFlag, i18n.LanguageEnglish)
                return
        }
 
+       acceptLang := strings.ReplaceAll(tag[0].String(), "-", "_")
+
+       for _, option := range translator.LanguageOptions {
+               if option.Value == acceptLang {
+                       ctx.Set(constant.AcceptLanguageFlag, 
i18n.Language(acceptLang))
+                       return
+               }
+       }
+
        // default language
        ctx.Set(constant.AcceptLanguageFlag, i18n.LanguageEnglish)
 }

Reply via email to