-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.go
60 lines (51 loc) · 1.12 KB
/
validate.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
package gos
import (
"errors"
"net/http"
"reflect"
"strings"
"github.com/go-playground/locales/zh"
"github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
tzh "github.com/go-playground/validator/v10/translations/zh"
)
var (
validate = validator.New()
zhTrans = ut.New(zh.New()).GetFallback()
)
func init() {
tzh.RegisterDefaultTranslations(validate, zhTrans)
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
if name == "-" {
return ""
}
if name == "" {
name = strings.SplitN(fld.Tag.Get("form"), ",", 2)[0]
if name == "-" {
return ""
}
}
return name
})
}
func isValidateErrorHandled(w http.ResponseWriter, err error, status *int) (handled bool) {
var vErrs validator.ValidationErrors
if errors.As(err, &vErrs) {
var fields = M{}
for _, ex := range vErrs {
fields = fields.Set(ex.Field(), ex.Translate(zhTrans))
}
*status = 400
Render(w,
M{
"code": "PARAM_ERROR",
"msg": "输入参数错误",
"data": fields,
},
status,
)
return true
}
return false
}