gin框架–路由参数

源码

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	r := gin.Default()

	// 此 handler 将匹配 /user/john 但不会匹配 /user/ 或者 /user
	r.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

	// 此 handler 将匹配 /user/john/ 和 /user/john/send
	// 如果没有其他路由匹配 /user/john,它将重定向到 /user/john/
	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)
	})

	r.Run(":8080")
}

注意: 使用 *action 后, action 包括了 / , 使用 :action 后, action 不包括 /

测试

http://127.0.0.1:8080/user/jhon
Hello jhon

http://127.0.0.1:8080/user/jhon/send
jhon is /send

gin官方文档 路由参数
https://gin-gonic.com/zh-cn/docs/examples/param-in-path/

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐