在 Gin 框架中,每个请求都会对应一个 *gin.Context,它就像一个临时管家/工具箱 ,帮助你处理请求和返回响应。理解 c *gin.Context 是学会 Gin 的关键。
1. *gin.Context 是什么
c *gin.Context 是 Gin 框架为每个请求创建的上下文对象,主要职责:
- 获取请求数据(路径、查询参数、请求体、请求头)
- 返回响应(JSON、字符串、文件等)
- 控制请求流程(中断、继续)
- 存储请求状态或共享数据(多个中间件/处理函数间传递数据)
可以把它理解成:
txt
浏览器请求 → Gin → c *gin.Context → 路由处理函数 → 响应返回
2. 基本使用
go
func CreateTodo(c *gin.Context) {
// c 是 Gin 自动传给你的 Context
title := c.Query("title") // 获取 URL ?title=xxx
id := c.Param("id") // 获取 URL /todo/:id
token := c.GetHeader("Authorization") // 获取请求头
c.JSON(200, gin.H{
"id": id,
"title": title,
"token": token,
})
}
3. 获取请求数据
3.1 URL 路径参数
go
r.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id") // 获取 /users/5 的 id=5
})
3.2 URL 查询参数
go
r.GET("/search", func(c *gin.Context) {
name := c.Query("name") // 获取 /search?name=zhangsan
})
3.3 请求体(Body)
go
type Todo struct {
Title string `json:"title"`
}
r.POST("/todos", func(c *gin.Context) {
var body Todo
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"title": body.Title})
})
3.4 请求头
go
token := c.GetHeader("Authorization")
4. 返回响应
*gin.Context 提供丰富的响应方法:
| 方法 | 作用 |
|---|---|
c.String(status, "内容") |
返回字符串 |
c.JSON(status, gin.H{...}) |
返回 JSON |
c.XML(status, obj) |
返回 XML |
c.Data(status, mimeType, bytes) |
返回原始数据 |
c.File("path") |
返回文件 |
示例:
go
c.JSON(200, gin.H{
"msg": "success",
"data": body,
})
5. 控制请求流程
- 继续执行下一个中间件或处理函数
go
c.Next()
- 中断请求,不再执行后续中间件/处理函数
go
c.Abort()
6. 在中间件中传递数据
*gin.Context 可以在中间件和路由处理函数之间传递数据:
go
r.Use(func(c *gin.Context) {
c.Set("userId", 1001) // 设置值
c.Next()
})
r.GET("/profile", func(c *gin.Context) {
userId, exists := c.Get("userId")
if exists {
c.JSON(200, gin.H{"userId": userId})
}
})
7. 总结
c *gin.Context 的核心概念:
- 每个请求独立创建,线程安全
- 负责整个请求生命周期:获取请求 → 处理请求 → 返回响应
- 中间件和路由共享数据 ,通过
Set和Get - 提供丰富方法:获取参数、获取请求头、绑定 JSON、返回各种类型响应
- 控制请求流程 :
Next()/Abort()
掌握 *gin.Context,你就掌握了 Gin 的核心管家,任何请求处理、参数获取、响应返回都离不开它。