Skip to content

Commit

Permalink
Fix validator's translator init issue
Browse files Browse the repository at this point in the history
This issue may cause an unrecoverable panic when concurrent requests to the server with the wrong parameters.
  • Loading branch information
0xJacky committed Apr 23, 2022
1 parent 8b60d61 commit 74a48d3
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions server/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,22 @@ type ValidError struct {
Message string
}

var trans ut.Translator

func init() {
uni := ut.New(zh.New())
trans, _ = uni.GetTranslator("zh")
v, ok := binding.Validator.Engine().(*val.Validate)
if ok {
_ = zhTranslations.RegisterDefaultTranslations(v, trans)
}
}

func BindAndValid(c *gin.Context, target interface{}) bool {
errs := make(map[string]string)
err := c.ShouldBindJSON(target)
if err != nil {
log.Println("raw err", err)
uni := ut.New(zh.New())
trans, _ := uni.GetTranslator("zh")
v, ok := binding.Validator.Engine().(*val.Validate)
if ok {
_ = zhTranslations.RegisterDefaultTranslations(v, trans)
}

verrs, ok := err.(val.ValidationErrors)

Expand Down

0 comments on commit 74a48d3

Please sign in to comment.