gin的占位符:和通配符*

本文详细解读Gin中通配符和占位符在路由配置中的使用方法及注意事项,涉及连续占位符、连续通配符示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、用法

在 Gin 路由中,可以使用一个通配符(*)或一个占位符(:)来捕获 URL 的一部分。

	r.GET("/royal/:id", func(c *gin.Context) {
		id := c.Param("id")

		//fmt.Println("into :id")
		c.String(http.StatusOK, "into :id, id is: "+id)

	})

	r.GET("royal2/*name", func(c *gin.Context) {
		name := c.Param("name")

		//fmt.Println("into *name")
		c.String(http.StatusOK, "into *name, name is: "+name)
	})

在这里插入图片描述
在这里插入图片描述
通配符表示的整个路径,并且会加上/。
在这里插入图片描述
如果通配符什么都不带,则返回的是一个/。
占位符则是用来获取一个路径段的参数:
在这里插入图片描述
但如果是占位符后面再跟路由,会报404
在这里插入图片描述
占位符注册的路由以后,可以注册相同前缀的路由。
比如用占位符注册了/royal/:id,可以继续注册/royal/123,并且访问/royal/123会精确匹配注册的路由。

	r.GET("/royal/123", func(c *gin.Context) {
		//id := c.Param("id")

		//fmt.Println("into :id")
		c.String(http.StatusOK, "into /royal/123")

	})

在这里插入图片描述
但如果是通配符,则不可以,会报panic。

	r.GET("royal2/*name", func(c *gin.Context) {
		name := c.Param("name")

		//fmt.Println("into *name")
		c.String(http.StatusOK, "into *name, name is: "+name)
	})

在这里插入图片描述

2、连续占位符

同一个路由中,允许多个占位符。

	r.GET("/royal3/:id/123/:id", func(c *gin.Context) {
		id := c.Param("id")

		//fmt.Println("into :id")
		c.String(http.StatusOK, "/royal3/:id/123/:id"+", id is: "+id)

	})

在这里插入图片描述
查看源码发现,Param会匹配第一个相同的key,也就是第一个id。

3、连续通配符

	r.GET("royal5/*id/123/*name", func(c *gin.Context) {
		name := c.Param("name")
		id := c.Param("id")
		fmt.Println("into *name")
		c.String(http.StatusOK, "id is: "+id+", name is:"+name)
	})

连续通配符会panic
在这里插入图片描述

4、通配符与占位符的使用

同一路由中,通配符和占位符可以同时使用,但是占位符要在通配符的前面,否则会panic

	r.GET("/royal6/*name/:id", func(c *gin.Context) {
		id := c.Param("id")

		fmt.Println("into :id")
		c.String(http.StatusOK, "hello "+id)
	})

在这里插入图片描述

	r.GET("royal1/:id/*name", func(c *gin.Context) {
		name := c.Param("name")
		id := c.Param("id")
		fmt.Println("into *name")
		c.String(http.StatusOK, "id is: "+id+", name is:"+name)
	})

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值