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
package main

import (
	"encoding/json"
	"fmt"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	"github.com/go-playground/locales/zh_Hant_TW"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	entranslations "github.com/go-playground/validator/v10/translations/en"
	zhtranslations "github.com/go-playground/validator/v10/translations/zh"
	zhtwtranslations "github.com/go-playground/validator/v10/translations/zh_tw"
	"reflect"
	"strings"
)

type InternalAccountTransferRequest struct {
	Name  string `json:"name" binding:"required"`
	Age   string `json:"age_test" binding:"required"`
	Class string `binding:"required"`
}

func main() {
	s := `{"name": "123"}`
	var requset InternalAccountTransferRequest
	json.Unmarshal([]byte(s), &requset)
	//requset.Class = "123"

	v := validator.New()

	var err error
	uni := ut.New(en.New(), en.New(), zh_Hant_TW.New(), zh.New())

	zh_, _ := uni.GetTranslator("zh")
	zhtranslations.RegisterDefaultTranslations(v, zh_)
	tw_, _ := uni.GetTranslator("zh_Hant_TW")
	zhtwtranslations.RegisterDefaultTranslations(v, tw_)
	en_, _ := uni.GetTranslator("en")

	err = entranslations.RegisterDefaultTranslations(v, en_)
	if err != nil {
		panic(err)
	}

	v.RegisterTagNameFunc(func(fld reflect.StructField) string {
		name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]

		if name == "-" {
			return ""
		}

		return name
	})
	v.SetTagName("binding")
	err = v.Struct(requset)
	fmt.Println("validErr:", err)
	errs := err.(validator.ValidationErrors)
	fmt.Println(errs.Translate(zh_))
	fmt.Println(errs.Translate(en_))
	fmt.Println(errs.Translate(tw_))
}