2
获取"/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 {

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

}


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

clipboard.png


厚朴酚XZ9lr
11 声望2 粉丝

c++/node.js/electron/vue.js/java