明智的是,Iris不提供内置数据验证。但是,它允许您附加一个验证器,该验证器将自动调用诸如Context之类的方法。ReadJSON ReadXML… 在这个示例中,我们将学习如何使用go-playground/validator/v10进行请求体验证。
在这里检查完整的文档和结构标记的用法。
$ go get github.com/go-playground/validator/v10@latest
注意,您需要在所有想要绑定的字段上设置相应的绑定标记。例如,当从JSON绑定时,设置JSON:“fieldname”。
package main
import (
"fmt"
"github.com/kataras/iris/v12"
"github.com/go-playground/validator/v10"
)
// User contains user information.
type User struct {
FirstName string `json:"fname"`
LastName string `json:"lname"`
Age uint8 `json:"age" validate:"gte=0,lte=130"`
Email string `json:"email" validate:"required,email"`
FavouriteColor string `json:"favColor" validate:"hexcolor|rgb|rgba"`
Addresses []*Address `json:"addresses" validate:"required,dive,required"`
}
// Address houses a users address information.
type Address struct {
Street string `json:"street" validate:"required"`
City string `json:"city" validate:"required"`
Planet string `json:"planet" validate:"required"`
Phone string `json:"phone" validate:"required"`
}
func main() {
// Use a single instance of Validate, it caches struct info.
//使用Validate的单个实例,它会缓存结构信息。
v := validator.New()
// Register a custom struct validation for 'User'
// NOTE: only have to register a non-pointer type for 'User', validator
// internally dereferences during it's type checks.
//为“User”注册自定义结构验证
//注意:只需要为'User', validator注册一个非指针类型
//在类型检查期间内部解除引用。
v.RegisterStructValidation(UserStructLevelValidation, User{})
app := iris.New()
// Register the validator to the Iris Application.
app.Validator = v
app.Post("/user", func(ctx iris.Context) {
var user User
// Returns InvalidValidationError for bad validation input,
// 如果验证输入错误,返回InvalidValidationError,
// nil or ValidationErrors ( []FieldError )
err := ctx.ReadJSON(&user)
if err != nil {
// This check is only needed when your code could produce
// an invalid value for validation such as interface with nil
// value most including myself do not usually have code like this.
//这个检查只在你的代码可以生成的时候才需要
//一个无效的验证值,比如nil接口
//大多数人,包括我自己,通常没有这样的代码。
if _, ok := err.(*validator.InvalidValidationError); ok {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.WriteString(err.Error())
return
}
ctx.StatusCode(iris.StatusBadRequest)
for _, err := range err.(validator.ValidationErrors) {
fmt.Println()
fmt.Println(err.Namespace())
fmt.Println(err.Field())
fmt.Println(err.StructNamespace())
fmt.Println(err.StructField())
fmt.Println(err.Tag())
fmt.Println(err.ActualTag())
fmt.Println(err.Kind())
fmt.Println(err.Type())
fmt.Println(err.Value())
fmt.Println(err.Param())
fmt.Println()
}
return
}
// [save user to database...]
})
app.Listen(":8080")
}
func UserStructLevelValidation(sl validator.StructLevel) {
user := sl.Current().Interface().(User)
if len(user.FirstName) == 0 && len(user.LastName) == 0 {
sl.ReportError(user.FirstName, "FirstName", "fname", "fnameorlname", "")
sl.ReportError(user.LastName, "LastName", "lname", "fnameorlname", "")
}
}
JSON形式的请求示例:
{
"fname": "",
"lname": "",
"age": 45,
"email": "mail@example.com",
"favColor": "#000",
"addresses": [{
"street": "Eavesdown Docks",
"planet": "Persphone",
"phone": "none",
"city": "Unknown"
}]
}
示例可以在以下地址找到: https://github.com/kataras/iris/tree/master/_examples/request-body/read-json-struct-validation/main.go。