[go-每日一库] golang gin框架路由设置(全面)

1.一般路由设置

...
  r.Any("/ping", anything)
    // r.POST("/post", posting)
	// r.PUT("/put", putting)
	// r.DELETE("/delete", deleting)
	// r.PATCH("/patch", patching)
	// r.HEAD("/head", head)
	// r.OPTIONS("/options", options)
...

2.动态路由设置

当我们需要动态参数的路由时,如 /user/:id,通过调用不同的参数 :id 动态获取相应的用户信息。其中 /user/:id/*type*type 的参数为可选。
示例:

r.Get("/:userid", handlefunc)

3.可选路由设置

示例:

r.Get("/user/*type", handlefunc)

4.组路由设置

示例:

...
  group := r.Group("/api/v1") // 也可以在此处加上中间件
  {
    group.Get("/index", index)
    group.Get("/:userid", doSmoething)
    ...
  }

5.解析参数

5.1 解析query参数

示例:

// 匹配 /search?keyword=xxx&weight=xxx ,weight可选
    r.GET("/search", func(c *gin.Context) {
        keyword := c.Query("keyword")
        weight := c.DefaultQuery("weight", "")
        c.JSON(200, gin.H{
            "keyword": keyword,
            "weight":  weight,
        })
    })

5.2 解析form表单参数

示例:

// POST application/x-www-form-urlencoded
    r.POST("/login", func(c *gin.Context) {
        username := c.PostForm("username")
        pwd := c.PostForm("pwd")
        c.JSON(200, gin.H{
            "username": username,
            "pwd":      pwd,
        })
    })

5.3 解析body-json参数

ShouldBindJson -> 一次解析,再次解析EOF, ShouldBindBodyWith -> 支持多次解析不出错

示例:

// ### 4.接收JSON参数
    // 定义接收 User 的结构体
    type User struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }
    r.POST("/json", func(c *gin.Context) {
        var user User
        err := c.BindJSON(&user) // ShouldBindJson -> 一次解析,再次解析EOF, ShouldBindBodyWith -> 支持多次解析不出错
        if err != nil {
            c.JSON(200, gin.H{"code": 400, "msg": "error", "data": nil})
            return
        } else {
            c.JSON(200, gin.H{"code": 0, "msg": "success", "data": user})
        }
    })

5.4 解析url中的动态路由的值

示例:

  // .../:userid/...
  userid := ctx.Param("userid")

参考:

posted on 2022-06-22 16:43  进击的davis  阅读(815)  评论(0编辑  收藏  举报

导航