内置中间件 #
一、内置中间件概述 #
Fiber提供了丰富的内置中间件,开箱即用。
1.1 常用内置中间件 #
| 中间件 | 功能 |
|---|---|
| logger | 请求日志记录 |
| recover | 错误恢复 |
| cors | 跨域处理 |
| helmet | 安全头设置 |
| compress | 响应压缩 |
| limiter | 请求限流 |
| requestid | 请求ID |
| timeout | 请求超时 |
二、Logger中间件 #
2.1 基本使用 #
go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
)
func main() {
app := fiber.New()
// 使用默认配置
app.Use(logger.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
app.Listen(":3000")
}
2.2 自定义配置 #
go
app.Use(logger.New(logger.Config{
// 输出格式
Format: "[${time}] ${status} - ${latency} ${method} ${path}\n",
// 时间格式
TimeFormat: "2006-01-02 15:04:05",
// 时区
TimeZone: "Asia/Shanghai",
// 输出目标
Output: os.Stdout,
// 是否禁用颜色
DisableColors: false,
}))
2.3 格式占位符 #
go
app.Use(logger.New(logger.Config{
Format: "${ip} - [${time}] ${method} ${path} ${status} ${latency}\n",
}))
// 可用占位符:
// ${ip} - 客户端IP
// ${ips} - 代理IP列表
// ${host} - 主机名
// ${method} - HTTP方法
// ${path} - 请求路径
// ${protocol} - 协议
// ${route} - 路由名称
// ${status} - 状态码
// ${latency} - 响应时间
// ${time} - 时间戳
// ${referer} - 来源页面
// ${ua} - User-Agent
// ${body} - 请求体
// ${reqHeader} - 请求头
// ${resHeader} - 响应头
2.4 输出到文件 #
go
file, err := os.OpenFile("./logs/app.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
app.Use(logger.New(logger.Config{
Output: file,
}))
三、Recover中间件 #
3.1 基本使用 #
go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/recover"
)
func main() {
app := fiber.New()
// 恢复panic
app.Use(recover.New())
app.Get("/", func(c *fiber.Ctx) error {
panic("Something went wrong!")
})
app.Listen(":3000")
}
3.2 自定义配置 #
go
app.Use(recover.New(recover.Config{
// 启用恢复
Enable: true,
// 自定义错误处理
ErrorHandler: func(c *fiber.Ctx, err error) error {
return c.Status(500).JSON(fiber.Map{
"error": "Internal Server Error",
})
},
}))
四、CORS中间件 #
4.1 基本使用 #
go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
func main() {
app := fiber.New()
// 使用默认配置(允许所有来源)
app.Use(cors.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"message": "Hello"})
})
app.Listen(":3000")
}
4.2 自定义配置 #
go
app.Use(cors.New(cors.Config{
// 允许的来源
AllowOrigins: "https://example.com, https://api.example.com",
// 允许的方法
AllowMethods: "GET,POST,PUT,DELETE,OPTIONS",
// 允许的请求头
AllowHeaders: "Content-Type, Authorization",
// 允许携带凭证
AllowCredentials: true,
// 暴露的响应头
ExposeHeaders: "Content-Length, X-Custom-Header",
// 预检请求缓存时间
MaxAge: 86400,
}))
4.3 动态来源 #
go
app.Use(cors.New(cors.Config{
AllowOriginsFunc: func(origin string) bool {
// 动态判断是否允许
return strings.HasSuffix(origin, ".example.com")
},
}))
五、Helmet中间件 #
5.1 基本使用 #
go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/helmet"
)
func main() {
app := fiber.New()
// 安全头设置
app.Use(helmet.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello")
})
app.Listen(":3000")
}
5.2 自定义配置 #
go
app.Use(helmet.New(helmet.Config{
XSSProtection: "1; mode=block",
ContentTypeNosniff: "nosniff",
XFrameOptions: "SAMEORIGIN",
HSTSMaxAge: 31536000,
HSTSIncludeSubdomains: true,
ContentSecurityPolicy: "default-src 'self'",
}))
六、Compress中间件 #
6.1 基本使用 #
go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
)
func main() {
app := fiber.New()
// 响应压缩
app.Use(compress.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Large content here...")
})
app.Listen(":3000")
}
6.2 压缩级别 #
go
app.Use(compress.New(compress.Config{
// 压缩级别
Level: compress.LevelBestSpeed, // 最快速度
// Level: compress.LevelBestCompression, // 最佳压缩
// Level: compress.LevelDefault, // 默认
}))
七、Limiter中间件 #
7.1 基本使用 #
go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/limiter"
)
func main() {
app := fiber.New()
// 请求限流
app.Use(limiter.New(limiter.Config{
Max: 100, // 最大请求数
Expiration: 1 * time.Minute, // 时间窗口
}))
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello")
})
app.Listen(":3000")
}
7.2 自定义配置 #
go
app.Use(limiter.New(limiter.Config{
// 最大请求数
Max: 100,
// 时间窗口
Expiration: 1 * time.Minute,
// 存储后端
Storage: memory.New(),
// 限流键生成
KeyGenerator: func(c *fiber.Ctx) string {
return c.IP()
},
// 限流响应
LimitReached: func(c *fiber.Ctx) error {
return c.Status(429).JSON(fiber.Map{
"error": "Too many requests",
})
},
// 跳过条件
Next: func(c *fiber.Ctx) bool {
return c.Path() == "/health"
},
}))
八、RequestID中间件 #
8.1 基本使用 #
go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/requestid"
)
func main() {
app := fiber.New()
// 请求ID
app.Use(requestid.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"request_id": c.Locals("requestid"),
})
})
app.Listen(":3000")
}
8.2 自定义配置 #
go
app.Use(requestid.New(requestid.Config{
// 请求头名称
Header: "X-Request-ID",
// 生成器
Generator: func() string {
return uuid.New().String()
},
// 上下文键名
ContextKey: "requestid",
}))
九、Timeout中间件 #
9.1 基本使用 #
go
package main
import (
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/timeout"
)
func main() {
app := fiber.New()
// 超时控制
app.Get("/slow", timeout.New(func(c *fiber.Ctx) error {
time.Sleep(3 * time.Second)
return c.SendString("Done")
}, 2*time.Second))
app.Listen(":3000")
}
9.2 超时处理 #
go
app.Get("/api", timeout.New(func(c *fiber.Ctx) error {
// 长时间操作
return c.JSON(fiber.Map{"data": "result"})
}, 5*time.Second, timeout.WithTimeoutHandler(func(c *fiber.Ctx) error {
return c.Status(408).JSON(fiber.Map{
"error": "Request timeout",
})
})))
十、其他常用中间件 #
10.1 Favicon中间件 #
go
import "github.com/gofiber/fiber/v2/middleware/favicon"
app.Use(favicon.New(favicon.Config{
File: "./static/favicon.ico",
}))
10.2 Static中间件 #
go
import "github.com/gofiber/fiber/v2/middleware/static"
app.Use("/static", static.New("./public", static.Config{
Browse: true,
Index: "index.html",
}))
10.3 KeyAuth中间件 #
go
import "github.com/gofiber/fiber/v2/middleware/keyauth"
app.Use(keyauth.New(keyauth.Config{
Validator: func(c *fiber.Ctx, key string) (bool, error) {
return key == "valid-api-key", nil
},
}))
10.4 Proxy中间件 #
go
import "github.com/gofiber/fiber/v2/middleware/proxy"
app.Get("/api/*", proxy.Forward("http://backend:8080"))
10.5 ETag中间件 #
go
import "github.com/gofiber/fiber/v2/middleware/etag"
app.Use(etag.New(etag.Config{
Weak: true,
}))
十一、中间件组合 #
11.1 标准组合 #
go
func main() {
app := fiber.New()
// 1. 错误恢复
app.Use(recover.New())
// 2. 请求ID
app.Use(requestid.New())
// 3. 日志记录
app.Use(logger.New())
// 4. 安全头
app.Use(helmet.New())
// 5. CORS
app.Use(cors.New())
// 6. 压缩
app.Use(compress.New())
// 7. 限流
app.Use(limiter.New())
// 业务路由...
app.Listen(":3000")
}
11.2 按需组合 #
go
func main() {
app := fiber.New()
// 全局中间件
app.Use(recover.New())
app.Use(logger.New())
// API分组
api := app.Group("/api")
api.Use(cors.New())
api.Use(limiter.New())
// 公开API
api.Get("/public", publicHandler)
// 认证API
auth := api.Group("/auth", keyauth.New())
auth.Get("/private", privateHandler)
app.Listen(":3000")
}
十二、总结 #
12.1 内置中间件一览 #
| 中间件 | 用途 | 推荐场景 |
|---|---|---|
| logger | 日志记录 | 所有项目 |
| recover | 错误恢复 | 所有项目 |
| cors | 跨域处理 | API服务 |
| helmet | 安全头 | Web应用 |
| compress | 响应压缩 | 大响应体 |
| limiter | 请求限流 | 公开API |
| requestid | 请求追踪 | 微服务 |
| timeout | 超时控制 | 长请求 |
12.2 下一步 #
现在你已经了解了内置中间件,接下来让我们学习 自定义中间件,编写自己的中间件!
最后更新:2026-03-28