当前位置: 首页 > news >正文

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

在这里插入图片描述
在这里插入图片描述
通配符表示的整个路径,并且会加上/。
在这里插入图片描述
如果通配符什么都不带,则返回的是一个/。
占位符则是用来获取一个路径段的参数:
在这里插入图片描述
但如果是占位符后面再跟路由,会报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)})

在这里插入图片描述

http://www.lryc.cn/news/123809.html

相关文章:

  • 【量化课程】08_2.深度学习量化策略基础实战
  • 12-数据结构-数组、矩阵、广义表
  • Idea 反编译jar包
  • 【Git】安装以及基本操作
  • Spring创建Bean的过程(2)
  • Linux 终端操作命令(2)内部命令
  • 【Git】大大大问题之syntax error near unexpected token `(‘ 的错误解决办法
  • Flink源码之TaskManager启动流程
  • 加入微软MCPP有什么优势?
  • leetcode做题笔记78子集
  • Skywalking-9.6.0系列之本地源码编译并启动
  • proteus结合keil-arm编译器构建STM32单片机项目进行仿真
  • 第五十三天
  • gorm基本操作
  • 华为OD机试 - 排队游戏(Java JS Python)
  • 滚动条样式更改
  • 掌握Python的X篇_33_MATLAB的替代组合NumPy+SciPy+Matplotlib
  • Python解决-力扣002-两数相加
  • nginx基于源码安装的方式对静态页面、虚拟主机(IP、端口、域名)和日志文件进行配置
  • [FPAG开发]使用Vivado创建第一个程序
  • 使用 Python 在 NLP 中进行文本预处理
  • [足式机器人]Part3机构运动微分几何学分析与综合Ch03-1 空间约束曲线与约束曲面微分几何学——【读书笔记】
  • pytest框架快速进阶篇-pytest前置和pytest后置,skipif跳过用例
  • Python 基础语法 | 常量表达式,变量,注释,输入输出
  • SQL | 分组数据
  • 软件测试技术之如何编写测试用例(6)
  • 论文阅读——Adversarial Eigen Attack on Black-Box Models
  • 自然语言处理从入门到应用——LangChain:记忆(Memory)-[自定义对话记忆与自定义记忆类]
  • 【C/C++】STL queue 非线程安全接口,危险!
  • 执行Lua脚本后一直查询不到Redis中的数据(附带问题详细排查过程,一波三折)