Context上下文 #
一、Context概述 #
1.1 什么是Context #
Context(上下文)是Fiber框架的核心对象,封装了HTTP请求和响应的所有信息,贯穿整个请求生命周期。
go
func handler(c *fiber.Ctx) error {
// c 就是 Context 对象
return c.SendString("Hello")
}
1.2 Context的作用 #
| 作用 | 说明 |
|---|---|
| 请求信息 | 获取请求参数、请求头、请求体 |
| 响应处理 | 设置响应状态、响应头、响应体 |
| 数据传递 | 在中间件和处理函数间传递数据 |
| 流程控制 | 控制请求处理流程 |
二、请求信息 #
2.1 基本请求信息 #
go
app.Get("/info", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"method": c.Method(), // HTTP方法
"path": c.Path(), // 请求路径
"hostname": c.Hostname(), // 主机名
"protocol": c.Protocol(), // 协议(http/https)
"ip": c.IP(), // 客户端IP
"ips": c.IPs(), // 代理IP列表
"isHTTPS": c.Secure(), // 是否HTTPS
"userAgent": c.Get("User-Agent"),
"referer": c.Get("Referer"),
"contentType": c.Get("Content-Type"),
})
})
2.2 获取请求头 #
go
app.Get("/headers", func(c *fiber.Ctx) error {
// 获取单个请求头
auth := c.Get("Authorization")
contentType := c.Get("Content-Type")
// 获取所有请求头
c.Request().Header.VisitAll(func(key, value []byte) {
fmt.Printf("%s: %s\n", key, value)
})
// 快捷方法
host := c.Hostname()
accept := c.Get("Accept")
return c.JSON(fiber.Map{
"authorization": auth,
"content-type": contentType,
})
})
2.3 获取请求体 #
go
app.Post("/body", func(c *fiber.Ctx) error {
// 原始Body
body := c.Body()
// Body字符串
bodyStr := c.BodyString()
return c.Send(body)
})
三、参数获取 #
3.1 路径参数 #
go
// 必需参数
app.Get("/users/:id", func(c *fiber.Ctx) error {
id := c.Params("id")
return c.SendString("User ID: " + id)
})
// 可选参数
app.Get("/posts/:id?", func(c *fiber.Ctx) error {
id := c.Params("id", "default")
return c.SendString("Post ID: " + id)
})
// 整数参数
app.Get("/page/:num", func(c *fiber.Ctx) error {
num := c.ParamsInt("num", 1)
return c.SendString("Page: " + strconv.Itoa(num))
})
// 通配符
app.Get("/files/*", func(c *fiber.Ctx) error {
path := c.Params("*")
return c.SendString("File: " + path)
})
3.2 查询参数 #
go
app.Get("/search", func(c *fiber.Ctx) error {
// 单个参数
q := c.Query("q")
page := c.Query("page", "1")
// 整数参数
limit := c.QueryInt("limit", 10)
// 布尔参数
active := c.QueryBool("active", false)
// 浮点参数
price := c.QueryFloat("price", 0.0)
// 所有参数
params := c.Queries()
return c.JSON(fiber.Map{
"q": q,
"page": page,
"limit": limit,
"active": active,
"price": price,
"all": params,
})
})
3.3 表单参数 #
go
app.Post("/form", func(c *fiber.Ctx) error {
// 单个参数
username := c.FormValue("username")
password := c.FormValue("password", "")
return c.JSON(fiber.Map{
"username": username,
"password": password,
})
})
3.4 解析到结构体 #
go
type UserQuery struct {
Name string `query:"name"`
Age int `query:"age"`
Email string `query:"email"`
}
app.Get("/users", func(c *fiber.Ctx) error {
var query UserQuery
if err := c.QueryParser(&query); err != nil {
return err
}
return c.JSON(query)
})
type UserBody struct {
Name string `json:"name"`
Email string `json:"email"`
}
app.Post("/users", func(c *fiber.Ctx) error {
var user UserBody
if err := c.BodyParser(&user); err != nil {
return err
}
return c.JSON(user)
})
四、响应处理 #
4.1 设置状态码 #
go
app.Get("/status", func(c *fiber.Ctx) error {
// 设置状态码
return c.Status(200).SendString("OK")
})
app.Get("/created", func(c *fiber.Ctx) error {
return c.Status(fiber.StatusCreated).JSON(fiber.Map{
"id": 1,
})
})
app.Get("/error", func(c *fiber.Ctx) error {
return c.Status(400).JSON(fiber.Map{
"error": "Bad Request",
})
})
4.2 设置响应头 #
go
app.Get("/headers", func(c *fiber.Ctx) error {
// 设置单个响应头
c.Set("Content-Type", "application/json")
c.Set("X-Custom-Header", "value")
// 设置多个响应头
c.Set("Cache-Control", "no-cache")
c.Set("X-Request-ID", "12345")
return c.SendString("OK")
})
4.3 响应类型 #
go
// 字符串响应
app.Get("/string", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
// JSON响应
app.Get("/json", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"message": "Hello",
"status": "ok",
})
})
// XML响应
app.Get("/xml", func(c *fiber.Ctx) error {
return c.XML(fiber.Map{
"message": "Hello",
})
})
// HTML响应
app.Get("/html", func(c *fiber.Ctx) error {
return c.SendString("<h1>Hello, HTML!</h1>")
})
// 字节响应
app.Get("/bytes", func(c *fiber.Ctx) error {
return c.Send([]byte("Hello, Bytes!"))
})
4.4 文件响应 #
go
// 发送文件
app.Get("/file", func(c *fiber.Ctx) error {
return c.SendFile("./static/document.pdf")
})
// 下载文件
app.Get("/download", func(c *fiber.Ctx) error {
return c.Download("./static/document.pdf", "report.pdf")
})
4.5 重定向 #
go
// 临时重定向(302)
app.Get("/redirect", func(c *fiber.Ctx) error {
return c.Redirect("/new-url")
})
// 永久重定向(301)
app.Get("/permanent", func(c *fiber.Ctx) error {
return c.Redirect("/new-url", 301)
})
// 外部重定向
app.Get("/external", func(c *fiber.Ctx) error {
return c.Redirect("https://example.com")
})
五、Cookie操作 #
5.1 获取Cookie #
go
app.Get("/cookie", func(c *fiber.Ctx) error {
// 获取单个Cookie
session := c.Cookies("session")
token := c.Cookies("token", "default")
return c.JSON(fiber.Map{
"session": session,
"token": token,
})
})
5.2 设置Cookie #
go
app.Get("/set-cookie", func(c *fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "session",
Value: "abc123",
Expires: time.Now().Add(24 * time.Hour),
HTTPOnly: true,
Secure: true,
SameSite: "Lax",
})
return c.SendString("Cookie set")
})
5.3 删除Cookie #
go
app.Get("/clear-cookie", func(c *fiber.Ctx) error {
c.ClearCookie("session")
return c.SendString("Cookie cleared")
})
六、数据存储 #
6.1 Locals存储 #
go
// 中间件存储数据
func authMiddleware(c *fiber.Ctx) error {
user := &User{ID: 1, Name: "John"}
c.Locals("user", user)
c.Locals("role", "admin")
return c.Next()
}
// 处理函数获取数据
app.Get("/profile", authMiddleware, func(c *fiber.Ctx) error {
user := c.Locals("user").(*User)
role := c.Locals("role").(string)
return c.JSON(fiber.Map{
"user": user,
"role": role,
})
})
6.2 安全类型断言 #
go
func GetUser(c *fiber.Ctx) *User {
if user, ok := c.Locals("user").(*User); ok {
return user
}
return nil
}
func GetRole(c *fiber.Ctx) string {
if role, ok := c.Locals("role").(string); ok {
return role
}
return ""
}
七、请求流程控制 #
7.1 Next方法 #
go
func middleware(c *fiber.Ctx) error {
fmt.Println("Before")
err := c.Next() // 继续执行下一个处理函数
fmt.Println("After")
return err
}
7.2 终止请求 #
go
func authMiddleware(c *fiber.Ctx) error {
token := c.Get("Authorization")
if token == "" {
// 直接返回响应,终止请求
return c.Status(401).JSON(fiber.Map{
"error": "Unauthorized",
})
}
return c.Next()
}
八、Context方法汇总 #
8.1 请求方法 #
| 方法 | 说明 |
|---|---|
| c.Method() | HTTP方法 |
| c.Path() | 请求路径 |
| c.Hostname() | 主机名 |
| c.Protocol() | 协议 |
| c.IP() | 客户端IP |
| c.Get() | 获取请求头 |
| c.Params() | 路径参数 |
| c.Query() | 查询参数 |
| c.FormValue() | 表单参数 |
| c.Body() | 请求体 |
| c.Cookies() | Cookie |
8.2 响应方法 #
| 方法 | 说明 |
|---|---|
| c.Status() | 设置状态码 |
| c.Set() | 设置响应头 |
| c.Send() | 发送响应 |
| c.SendString() | 发送字符串 |
| c.JSON() | JSON响应 |
| c.XML() | XML响应 |
| c.SendFile() | 发送文件 |
| c.Download() | 下载文件 |
| c.Redirect() | 重定向 |
| c.Cookie() | 设置Cookie |
8.3 其他方法 #
| 方法 | 说明 |
|---|---|
| c.Next() | 继续执行 |
| c.Locals() | 本地存储 |
| c.Append() | 追加响应头 |
| c.Type() | 设置Content-Type |
| c.Attachment() | 设置附件 |
九、总结 #
9.1 核心要点 #
| 要点 | 说明 |
|---|---|
| 请求信息 | c.Method()、c.Path()、c.IP()等 |
| 参数获取 | c.Params()、c.Query()、c.FormValue() |
| 响应处理 | c.JSON()、c.SendString()、c.Status() |
| 数据存储 | c.Locals() |
| 流程控制 | c.Next() |
9.2 下一步 #
现在你已经了解了Context上下文,接下来让我们学习 请求处理,深入了解请求处理的细节!
最后更新:2026-03-28