-
Notifications
You must be signed in to change notification settings - Fork 5
/
translations.go
41 lines (38 loc) · 1.24 KB
/
translations.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
// locales 是语言包
"github.com/go-playground/locales/en"
"github.com/go-playground/locales/zh"
"github.com/go-playground/locales/zh_Hant_TW"
// 通用翻译器,是一个使用 CLDR 数据 + 复数规则的 Go 语言 i18n 转换器。
"github.com/go-playground/universal-translator"
validator "github.com/go-playground/validator/v10"
en_translations "github.com/go-playground/validator/v10/translations/en"
zh_translations "github.com/go-playground/validator/v10/translations/zh"
)
func Translations() gin.HandlerFunc {
return func(c *gin.Context) {
uni := ut.New(en.New(), zh.New(), zh_Hant_TW.New())
// 根据所在地翻译, 取TCP的Header为locale的值来加载不同的语言包
locale := c.GetHeader("locale")
trans, _ := uni.GetTranslator(locale)
v, ok := binding.Validator.Engine().(*validator.Validate)
if ok {
switch locale {
case "zh":
_ = zh_translations.RegisterDefaultTranslations(v, trans)
break
case "en":
_ = en_translations.RegisterDefaultTranslations(v, trans)
break
default:
_ = zh_translations.RegisterDefaultTranslations(v, trans)
break
}
c.Set("trans", trans)
}
c.Next()
}
}