明智的是,Iris不提供内置数据验证。但是,它允许您附加一个验证器,该验证器将自动调用诸如Context之类的方法。ReadJSON ReadXML… 在这个示例中,我们将学习如何使用go-playground/validator/v10进行请求体验证。

    这里检查完整的文档和结构标记的用法。

    1. $ go get github.com/go-playground/validator/v10@latest

    注意,您需要在所有想要绑定的字段上设置相应的绑定标记。例如,当从JSON绑定时,设置JSON:“fieldname”。

    1. package main
    2. import (
    3. "fmt"
    4. "github.com/kataras/iris/v12"
    5. "github.com/go-playground/validator/v10"
    6. )
    7. // User contains user information.
    8. type User struct {
    9. FirstName string `json:"fname"`
    10. LastName string `json:"lname"`
    11. Age uint8 `json:"age" validate:"gte=0,lte=130"`
    12. Email string `json:"email" validate:"required,email"`
    13. FavouriteColor string `json:"favColor" validate:"hexcolor|rgb|rgba"`
    14. Addresses []*Address `json:"addresses" validate:"required,dive,required"`
    15. }
    16. // Address houses a users address information.
    17. type Address struct {
    18. Street string `json:"street" validate:"required"`
    19. City string `json:"city" validate:"required"`
    20. Planet string `json:"planet" validate:"required"`
    21. Phone string `json:"phone" validate:"required"`
    22. }
    23. func main() {
    24. // Use a single instance of Validate, it caches struct info.
    25. //使用Validate的单个实例,它会缓存结构信息。
    26. v := validator.New()
    27. // Register a custom struct validation for 'User'
    28. // NOTE: only have to register a non-pointer type for 'User', validator
    29. // internally dereferences during it's type checks.
    30. //为“User”注册自定义结构验证
    31. //注意:只需要为'User', validator注册一个非指针类型
    32. //在类型检查期间内部解除引用。
    33. v.RegisterStructValidation(UserStructLevelValidation, User{})
    34. app := iris.New()
    35. // Register the validator to the Iris Application.
    36. app.Validator = v
    37. app.Post("/user", func(ctx iris.Context) {
    38. var user User
    39. // Returns InvalidValidationError for bad validation input,
    40. // 如果验证输入错误,返回InvalidValidationError,
    41. // nil or ValidationErrors ( []FieldError )
    42. err := ctx.ReadJSON(&user)
    43. if err != nil {
    44. // This check is only needed when your code could produce
    45. // an invalid value for validation such as interface with nil
    46. // value most including myself do not usually have code like this.
    47. //这个检查只在你的代码可以生成的时候才需要
    48. //一个无效的验证值,比如nil接口
    49. //大多数人,包括我自己,通常没有这样的代码。
    50. if _, ok := err.(*validator.InvalidValidationError); ok {
    51. ctx.StatusCode(iris.StatusInternalServerError)
    52. ctx.WriteString(err.Error())
    53. return
    54. }
    55. ctx.StatusCode(iris.StatusBadRequest)
    56. for _, err := range err.(validator.ValidationErrors) {
    57. fmt.Println()
    58. fmt.Println(err.Namespace())
    59. fmt.Println(err.Field())
    60. fmt.Println(err.StructNamespace())
    61. fmt.Println(err.StructField())
    62. fmt.Println(err.Tag())
    63. fmt.Println(err.ActualTag())
    64. fmt.Println(err.Kind())
    65. fmt.Println(err.Type())
    66. fmt.Println(err.Value())
    67. fmt.Println(err.Param())
    68. fmt.Println()
    69. }
    70. return
    71. }
    72. // [save user to database...]
    73. })
    74. app.Listen(":8080")
    75. }
    76. func UserStructLevelValidation(sl validator.StructLevel) {
    77. user := sl.Current().Interface().(User)
    78. if len(user.FirstName) == 0 && len(user.LastName) == 0 {
    79. sl.ReportError(user.FirstName, "FirstName", "fname", "fnameorlname", "")
    80. sl.ReportError(user.LastName, "LastName", "lname", "fnameorlname", "")
    81. }
    82. }

    JSON形式的请求示例:

    1. {
    2. "fname": "",
    3. "lname": "",
    4. "age": 45,
    5. "email": "mail@example.com",
    6. "favColor": "#000",
    7. "addresses": [{
    8. "street": "Eavesdown Docks",
    9. "planet": "Persphone",
    10. "phone": "none",
    11. "city": "Unknown"
    12. }]
    13. }

    示例可以在以下地址找到: https://github.com/kataras/iris/tree/master/_examples/request-body/read-json-struct-validation/main.go。