You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.1 KiB
66 lines
1.1 KiB
package util
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
ut "github.com/go-playground/universal-translator"
|
|
val "github.com/go-playground/validator/v10"
|
|
"strings"
|
|
)
|
|
|
|
/**
|
|
@author: sre
|
|
@date: 2022/8/19 0019
|
|
@desc: todo
|
|
**/
|
|
|
|
type ValidError struct {
|
|
Key string
|
|
Message string
|
|
}
|
|
|
|
type ValidErrors []*ValidError
|
|
|
|
func (v *ValidError) Error() string {
|
|
return v.Message
|
|
}
|
|
|
|
func (v ValidErrors) Error() string {
|
|
return strings.Join(v.Errors(), ",")
|
|
}
|
|
|
|
func (v ValidErrors) Errors() []string {
|
|
var errs []string
|
|
for _, err := range v {
|
|
errs = append(errs, err.Error())
|
|
}
|
|
|
|
return errs
|
|
}
|
|
|
|
// 判断变量是否符合要求
|
|
func BindAndValid(c *gin.Context, v any) (bool, ValidErrors) {
|
|
var errs ValidErrors
|
|
err := c.ShouldBind(v)
|
|
if err != nil {
|
|
v := c.Value("trans")
|
|
trans, _ := v.(ut.Translator)
|
|
verrs, ok := err.(val.ValidationErrors)
|
|
if !ok {
|
|
errs = append(errs, &ValidError{
|
|
Key: "field",
|
|
Message: err.Error(),
|
|
})
|
|
return false, errs
|
|
}
|
|
for key, value := range verrs.Translate(trans) {
|
|
errs = append(errs, &ValidError{
|
|
Key: key,
|
|
Message: value,
|
|
})
|
|
}
|
|
|
|
return false, errs
|
|
}
|
|
return true, nil
|
|
}
|