iris 并没有内置数据校验,所以使用go-playground的validator
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
func main() {
user := &User{
Name: "Mike",
Sex: "male",
}
validate := validator.New()
err := validate.Struct(user)
if err != nil {
fmt.Println("error")
return
}
fmt.Println("success")
}
// Address houses a users address information
type User struct {
Name string `validate:"required"`
Age int `validate:"required,gte=0,lte=130"`
Sex string `validate:"required"`
}
有疑问加站长微信联系(非本文作者)