feat: support i18n request headerkey (#1094)

Co-authored-by: ziv <xiaozheng@tuya.com>
This commit is contained in:
xiaoziv 2022-08-08 19:02:14 +08:00 committed by GitHub
parent 2c963258cf
commit bd0480216c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 0 deletions

View File

@ -4,6 +4,9 @@ RunMode = "release"
# # custom i18n dict config # # custom i18n dict config
# I18N = "./etc/i18n.json" # I18N = "./etc/i18n.json"
# # custom i18n request header key
# I18NHeaderKey = "X-Language"
# metrics descriptions # metrics descriptions
MetricsYamlFile = "./etc/metrics.yaml" MetricsYamlFile = "./etc/metrics.yaml"

View File

@ -78,6 +78,7 @@ func MustLoad(fpaths ...string) {
type Config struct { type Config struct {
RunMode string RunMode string
I18N string I18N string
I18NHeaderKey string
AdminRole string AdminRole string
MetricsYamlFile string MetricsYamlFile string
BuiltinAlertsDir string BuiltinAlertsDir string

View File

@ -31,6 +31,25 @@ func stat() gin.HandlerFunc {
} }
} }
func languageDetector() gin.HandlerFunc {
headerKey := config.C.I18NHeaderKey
return func(c *gin.Context) {
if headerKey != "" {
lang := c.GetHeader(headerKey)
if lang != "" {
if strings.HasSuffix(lang, "*") || strings.HasPrefix(lang, "zh") {
c.Header("X-Language", "zh")
} else if strings.HasPrefix(lang, "en") {
c.Header("X-Language", "en")
} else {
c.Header("X-Language", lang)
}
}
}
c.Next()
}
}
func New(version string) *gin.Engine { func New(version string) *gin.Engine {
gin.SetMode(config.C.RunMode) gin.SetMode(config.C.RunMode)
@ -41,6 +60,7 @@ func New(version string) *gin.Engine {
r := gin.New() r := gin.New()
r.Use(stat()) r.Use(stat())
r.Use(languageDetector())
r.Use(aop.Recovery()) r.Use(aop.Recovery())
// whether print access log // whether print access log