package controller import ( "fmt" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" "hy2xs-admin/model/constant" "hy2xs-admin/model/vo" "net/http" "regexp" ) var validate *validator.Validate func init() { validate = validator.New() _ = validate.RegisterValidation("validateStr", validateStr) } func validateStr(f validator.FieldLevel) bool { field := f.Field().String() // Строка должна быть длиной 6-32 символа и состоять из букв, цифр или разрешённых спецсимволов reg := "^[a-zA-Z0-9!@#$%^&*()_+-=]{6,32}$" compile := regexp.MustCompile(reg) return field == "" || compile.MatchString(field) } func validateField[T interface{}](c *gin.Context, field T) (T, error) { var bindErr error if c.Request.Method == http.MethodGet { bindErr = c.ShouldBindQuery(&field) } else if c.Request.Method == http.MethodPost || c.Request.Method == http.MethodPut || c.Request.Method == http.MethodPatch || c.Request.Method == http.MethodDelete { bindErr = c.ShouldBindJSON(&field) } if bindErr != nil { vo.Fail(constant.InvalidError, c) return field, fmt.Errorf(constant.InvalidError) } if err := validate.Struct(&field); err != nil { vo.Fail(constant.InvalidError, c) return field, fmt.Errorf(constant.InvalidError) } return field, nil }