Iris——整合go-playground/validator参数校验Demo
Posted Starzkg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Iris——整合go-playground/validator参数校验Demo相关的知识,希望对你有一定的参考价值。
源代码:https://gitee.com/shentuzhigang/mini-project/blob/master/iris_validator
解决方案
go.mod
require (
github.com/Joker/hpp v1.0.0 // indirect
github.com/go-playground/validator/v10 v10.6.1
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
github.com/kataras/iris/v12 v12.2.0-alpha2.0.20210616105239-6d3884b0ceba
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/yudai/pp v2.0.1+incompatible // indirect
)
main.go
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)
err := app.Listen(":8080")
if err != nil {
return
}
}
//{"name" : "Marx", "age" : 202}
func profile(ctx iris.Context) {
var user User
err := ctx.ReadJSON(&user)
if err != nil {
_, err := ctx.JSON("error")
if err != nil {
return
}
return
}
_, err = ctx.JSON("ok")
if err != nil {
return
}
}
type User struct {
Name string `json:"name" validate:"required"`
Age uint8 `json:"age" validate:"required,gte=0,lte=130"`
}
参考文章
以上是关于Iris——整合go-playground/validator参数校验Demo的主要内容,如果未能解决你的问题,请参考以下文章