پارامترها در مسیر
Gin از دو نوع پارامتر مسیر پشتیبانی میکند که به شما امکان میدهد مقادیر را مستقیماً از URL دریافت کنید:
:name— یک بخش مسیر را مطابقت میدهد. بهعنوان مثال،/user/:nameبا/user/johnمطابقت دارد اما با/user/یا/userمطابقت ندارد.*action— همه چیز پس از پیشوند، شامل اسلشها را مطابقت میدهد. بهعنوان مثال،/user/:name/*actionبا/user/john/sendو/user/john/مطابقت دارد. مقدار گرفتهشده شامل/ابتدایی است.
از c.Param("name") برای دریافت مقدار پارامتر مسیر در handler خود استفاده کنید.
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 /