- 简介
- 读取请求参数
- path 中的参数
- query 中的参数
- from 中的参数
- 模型绑定
- 返回响应
- 总结
- 当前部分的代码
简介
使用 web 框架, 最基础的事情就是读写请求了, Gin 支持很多种类的请求参数, 也支持多种格式的响应.
读取请求参数
path 中的参数
使用 Param()
可以获取 path 中的参数.
定义在 path 中的参数有两种格式, 一个是 :name
的以冒号开头的, 另一种是 *action
的以星号开头的.
:name
是必定匹配的, 一定要有值, 不能为空. 下面的代码中, 第一个例子就是如此, 用 :name
来表示用户的名字, 这样就可以在路径中表示任意的用户名了.
*action
是可选的, 如果不存在, 就会忽略掉, 比如是可以匹配到 /user/john/
的, 另外 /user/john
会被跳转到 /user/john/
.
// 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)
}