ginでHTTP RequestのPathParameterを受け取る

Path Parameterの後ろに階層がある場合

次のようなAPIを定義する

GET
/user/:name/profile

GET
/uesr/:name/history

これをginで実装する方法は公式ページにも紹介されている。

r.GET("/user/:name/*action", func(c *gin.Context) {
    name := c.Param("name")
    action := c.Param("action")
    message := name + " is " + action
    c.String(http.StatusOK, message)
})

もちろん単純に1つずつ実装しても動作する。

r.GET("/user/:name/profile", func(c *gin.Context) {
    name := c.Param("name")
    message := name + " profile"
    c.String(http.StatusOK, message)
})
r.GET("/user/:name/history", func(c *gin.Context) {
    name := c.Param("name")
    message := name + " history"
    c.String(http.StatusOK, message)
})

間に1つ以上の階層が挟まる場合

上で紹介したAPI:nameactionの間にgroupという階層を挟んだ例。

GET
/user/:name/group/profile

GET
/user/:name/group/history

これも同じ内容で実装できる。もちろん単純に1つずつ実装しても動作する。

r.GET("/user/:name/group/*action", func(c *gin.Context) {
    name := c.Param("name")
    action := c.Param("action")
    message := name + " is " + action
    c.String(http.StatusOK, message)
})

または、次のコードでも動作はできる。
ただし、この場合はaction = /group/profileのようにパスが渡される。

r.GET("/user/:name/*action", func(c *gin.Context) {
    name := c.Param("name")
    action := c.Param("action")
    message := name + " is " + action
    c.String(http.StatusOK, message)
})