美文网首页
gin 表单绑定结构体验证

gin 表单绑定结构体验证

作者: My_Fuzz | 来源:发表于2019-10-12 18:19 被阅读0次

    路由注册

        route := gin.Default()
        //注册验证模版
        if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
            v.RegisterValidation("bookabledate", bookableDate)
        }
        route.GET("/bookable", getBookable)
        route.Run(":8085")
    

    注册验证规则

    func bookableDate(
        v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
        field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
    ) bool {
        fmt.Println(topStruct,currentStructOrField,field,fieldType,fieldKind,param)
        if date, ok := field.Interface().(string); ok {
            if date == "1" {
                return false
            }
        }
        return true
    }
    

    定义接受结构体

    type Booking struct {
        CheckIn  string `form:"check_in" binding:"required,bookabledate"`
        CheckOut string `form:"check_out" binding:"required,bookabledate"`
    }
    

    控制器参数绑定

    func getBookable(c *gin.Context) {
        var b Booking
        if err := c.ShouldBindWith(&b, binding.Query); err == nil {
            fmt.Println(b)
            c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
        } else {
            c.JSON(http.StatusOK, gin.H{"error": err.Error()})
        }
    }
    

    相关文章

      网友评论

          本文标题:gin 表单绑定结构体验证

          本文链接:https://www.haomeiwen.com/subject/hlkcmctx.html