Iris 没有内建的方法来验证请求数据,例如 Models。然而,你并没有因此受到限制。在这个示例中,我们可以学习怎么使用 go-playground/validator.v9 来验证请求数据。

    1. $ go get gopkg.in/go-playground/validator.v9

    记住你需要在所有的字段设置相应的你想绑定的tag。例如,当你为 JSON 绑定时,设置 json:"fieldname"

    1. package main
    2. import (
    3. "fmt"
    4. "github.com/kataras/iris/v12"
    5. "gopkg.in/go-playground/validator.v9"
    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. // Use a single instance of Validate, it caches struct info.
    24. var validate *validator.Validate
    25. func main() {
    26. validate = validator.New()
    27. // Register 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. validate.RegisterStructValidation(UserStructLevelValidation, User{})
    31. app := iris.New()
    32. app.Post("/user", func(ctx iris.Context) {
    33. var user User
    34. if err := ctx.ReadJSON(&user); err != nil {
    35. // [handle error...]
    36. }
    37. // Returns InvalidValidationError for bad validation input,
    38. // nil or ValidationErrors ( []FieldError )
    39. err := validate.Struct(user)
    40. if err != nil {
    41. // This check is only needed when your code could produce
    42. // an invalid value for validation such as interface with nil
    43. // value most including myself do not usually have code like this.
    44. if _, ok := err.(*validator.InvalidValidationError); ok {
    45. ctx.StatusCode(iris.StatusInternalServerError)
    46. ctx.WriteString(err.Error())
    47. return
    48. }
    49. ctx.StatusCode(iris.StatusBadRequest)
    50. for _, err := range err.(validator.ValidationErrors) {
    51. fmt.Println()
    52. fmt.Println(err.Namespace())
    53. fmt.Println(err.Field())
    54. fmt.Println(err.StructNamespace())
    55. fmt.Println(err.StructField())
    56. fmt.Println(err.Tag())
    57. fmt.Println(err.ActualTag())
    58. fmt.Println(err.Kind())
    59. fmt.Println(err.Type())
    60. fmt.Println(err.Value())
    61. fmt.Println(err.Param())
    62. fmt.Println()
    63. }
    64. return
    65. }
    66. // [save user to database...]
    67. })
    68. app.Run(iris.Addr(":8080"))
    69. }
    70. func UserStructLevelValidation(sl validator.StructLevel) {
    71. user := sl.Current().Interface().(User)
    72. if len(user.FirstName) == 0 && len(user.LastName) == 0 {
    73. sl.ReportError(user.FirstName, "FirstName", "fname", "fnameorlname", "")
    74. sl.ReportError(user.LastName, "LastName", "lname", "fnameorlname", "")
    75. }
    76. }

    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. }