路径参数
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")}测试
# Single parameter -- matches :namecurl http://localhost:8080/user/john# Output: Hello john
# Wildcard parameter -- matches :name and *actioncurl http://localhost:8080/user/john/send# Output: john is /send
# Trailing slash is captured by the wildcardcurl http://localhost:8080/user/john/# Output: john is /