Gin框架-绑定uri

查看详细信息

package main

import "github.com/gin-gonic/gin"

type Person struct {
    ID string `uri:"id" binding:"required,uuid"`
    Name string `uri:"name" binding:"required"`
}

func main() {
    route := gin.Default()
    route.GET("/:name/:id", func(c *gin.Context) {
        var person Person
        if err := c.ShouldBindUri(&person); err != nil {
            c.JSON(400, gin.H{"msg": err})
            return
        }
        c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
    })
    route.Run(":8088")
}

测试用例:

$ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
$ curl -v localhost:8088/thinkerou/not-uuid

作者:正在修炼的西瓜君
链接:https://www.jianshu.com/p/98965b3ff638/
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

Leave a Reply

Your email address will not be published. Required fields are marked *