美文网首页Golang入坑之旅
Golang 之ShouldBind与binding验证学习

Golang 之ShouldBind与binding验证学习

作者: 写写而已 | 来源:发表于2019-10-30 22:54 被阅读0次
    package main
    // ShouldBind学习,验证和绑定
    import (
        "github.com/gin-gonic/gin"
        "time"
    )
    // 多个用,隔开,并列用|
    type Boy struct{
        Name string `form:"name" binding:"required"`
        Age int `form:"age" binding:"required,min=0,max=120"`
        Address string `form:"address"`
        Brithday time.Time `form:"brithday" time_format:"2006-01-02"`
    }
    func handleBoy(c *gin.Context) {
        var boy Boy
        if err := c.ShouldBind(&boy); err == nil {
            //c.String(200, "%v", boy)
            c.JSON(200, gin.H{
                "name": boy.Name,
                "age": boy.Age,
                "address": boy.Address,
                "brithday": boy.Brithday,
            })
        } else {
            c.JSON( 200, gin.H{
                "error": err.Error(),
            })
            //c.String(200, "%v", err)
        }
    }
    func main(){
        r := gin.Default()
        r.GET("/boy", handleBoy)
        r.Run(":2017")
    }
    

    相关文章

      网友评论

        本文标题:Golang 之ShouldBind与binding验证学习

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