[gin] 接收路由中的參數、請求中的資料或檔案
keywords: parameters
, querystring
, file
Parameters in Path
取得網址中的 params:
- 在路由設定中
- 使用
:<filed>
可以定義動態路由(只能匹配到/
以前) - 使用
*<filed>
可以定義動態路由(可以匹配到/
以後)
- 使用
c.Param("<field>")
可以取得網址中的參數c.Fullpath()
可以取得定義的路由參數
func main() {
router := gin.Default()
router.GET("/user", func(c *gin.Context) {
c.String(200, "/user")
})
// 不會匹配到 /user/ 或 /user
router.GET("/user/:name", func(c *gin.Context) {
fmt.Println(c.FullPath()) // /user/:name/
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// 然而,這將會匹配到 /user/john/ 和 /user/john/send
// If no other routers match /user/john, it will redirect to /user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {
fmt.Println(c.FullPath()) // /user/:name/*action
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
router.Run(":3000")
}