二 :gin web框架學習經常使用路由參數解析

獲取"/user/:name"的name參數
router.GET("/user/:name", func(c *gin.Context) {
                    name := c.Param("name")
                    c.JSON(http.StatusOK,gin.H{"name":name})
                })
/params?firstname=lcd&lastname=dong
router.GET("/params", func(context *gin.Context) {
            firstname := context.DefaultQuery("firstname","defaultName")
            lastname := context.Query("lastname")
            context.JSON(http.StatusOK,gin.H{
                "firstName":firstname,
                "lastName":lastname,
            })
        })
  • /params?firstname=lcd&lastname=dong
  • 返回結果: {"lastName",lin,"lastName":dong}
  • 對於context.DefaultQuery(key,defaultValue): 若是沒有指定字段,則給定key設置一個默認值,在分頁
Multipart/Urlencoded Form
router.POST("/form_post", func(c *gin.Context) {
            name := c.PostForm("name")
            nick := c.DefaultPostForm("age", "90")
    
            c.JSON(200, gin.H{
                "name": name,
                "age":    nick,
            })
        })
  • 測試

clipboard.png

post application/Json格式

type User struct {json

Username string `form:"username" json:"username" binding:"required"`
Passwd   string `form:"passwd" json:"passwd" bdinding:"required"`
Age      int    `form:"age" json:"age"`

}app

router.POST("/json", func(context *gin.Context) {
        var user User
        context.BindJSON(&user)
        context.JSON(200,gin.H{"data":user})
    })
  • 測試

clipboard.png

相關文章
相關標籤/搜索