-
Notifications
You must be signed in to change notification settings - Fork 0
/
validat.go
67 lines (60 loc) · 1.63 KB
/
validat.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package wed
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/locales/en"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
enTranslations "github.com/go-playground/validator/v10/translations/en"
chTranslations "github.com/go-playground/validator/v10/translations/zh"
)
var Trans ut.Translator
// loca 通常取决于 http 请求头的 'Accept-Language'
func translate(local string) (err error) {
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
zhT := zh.New() //chinese
enT := en.New() //english
uni := ut.New(enT, zhT, enT)
var o bool
Trans, o = uni.GetTranslator(local)
if !o {
return fmt.Errorf("uni.GetTranslator(%s) failed", local)
}
//register translate
// 注册翻译器
switch local {
case "en":
err = enTranslations.RegisterDefaultTranslations(v, Trans)
case "zh":
err = chTranslations.RegisterDefaultTranslations(v, Trans)
default:
err = enTranslations.RegisterDefaultTranslations(v, Trans)
}
return
}
return
}
func init() {
if err := translate("zh"); err != nil {
fmt.Println("验证器加载失败:", err)
return
}
}
//绑定校验
func BindErr(c *gin.Context, err error) {
errs, ok := err.(validator.ValidationErrors)
if !ok {
c.JSON(http.StatusOK, gin.H{
"code": 2,
"msg": err.Error(), // 非validator.ValidationErrors类型错误直接返回
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": errs.Translate(Trans),
})
}