gin的占位符:和通配符*

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)
	})

gin的占位符:和通配符*_第1张图片
gin的占位符:和通配符*_第2张图片
通配符表示的整个路径,并且会加上/。
gin的占位符:和通配符*_第3张图片
如果通配符什么都不带,则返回的是一个/。
占位符则是用来获取一个路径段的参数:
gin的占位符:和通配符*_第4张图片
但如果是占位符后面再跟路由,会报404
gin的占位符:和通配符*_第5张图片
占位符注册的路由以后,可以注册相同前缀的路由。
比如用占位符注册了/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")

	})

gin的占位符:和通配符*_第6张图片
但如果是通配符,则不可以,会报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)

	})

gin的占位符:和通配符*_第7张图片
查看源码发现,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)
	})

gin的占位符:和通配符*_第8张图片

你可能感兴趣的:(gin,ios)