iris 并没有内置数据校验,所以使用go-playground的validator
package main
import (
"github.com/go-playground/validator/v10"
"github.com/kataras/iris/v12"
)
func main() {
app := iris.New()
app.Validator = validator.New()
app.Post("/user", profile)
app.Listen(":8080")
}
//{"name" : "Marx", "age" : 202}
func profile(ctx iris.Context) {
var user User
err := ctx.ReadJSON(&user)
if err != nil {
ctx.JSON("error")
return
}
ctx.JSON("ok")
}
type User struct {
Name string `json:"name" validate:"required"`
Age uint8 `json:"age" validate:"required,gte=0,lte=130"`
}
网友评论