跳到內容

路徑參數

Gin 支援兩種類型的路徑參數,讓你可以直接從 URL 中擷取值:

  • :name —— 匹配單一路徑段。例如,/user/:name 匹配 /user/john,但匹配 /user//user
  • *action —— 匹配前綴之後的所有內容,包括斜線。例如,/user/:name/*action 匹配 /user/john/send/user/john/。擷取的值包含前導 /

使用 c.Param("name") 在處理器中取得路徑參數的值。

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// This handler will match /user/john but will not match /user/ or /user
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// However, this one will match /user/john/ and also /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) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
router.Run(":8080")
}

測試

Terminal window
# Single parameter -- matches :name
curl http://localhost:8080/user/john
# Output: Hello john
# Wildcard parameter -- matches :name and *action
curl http://localhost:8080/user/john/send
# Output: john is /send
# Trailing slash is captured by the wildcard
curl http://localhost:8080/user/john/
# Output: john is /

另請參閱