Fiber 框架参考
Go Fiber v2(Express 风格)完整参考:路由、中间件、ctx API、文件上传、WebSocket 和性能配置。
1. 初始化与路由
app := fiber.New(fiber.Config{
AppName: "My API v1.0",
ReadTimeout: 5 * time.Second,
BodyLimit: 4 * 1024 * 1024,
})
app.Use(logger.New())
app.Use(recover.New())
api := app.Group("/api/v1")
api.Get("/articles", listArticles)
api.Post("/articles", createArticle)
api.Get("/articles/:id", getArticle)
app.Listen(":8080")
2. ctx 方法
func handler(c *fiber.Ctx) error {
id := c.Params("id")
page := c.Query("page", "1")
auth := c.Get("Authorization")
var req CreateRequest
if err := c.BodyParser(&req); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
c.Locals("user", currentUser)
return c.JSON(fiber.Map{"ok": true})
}
3. 中间件
app.Use(cors.New(cors.Config{
AllowOrigins: "https://app.example.com",
AllowMethods: "GET,POST,PUT,DELETE",
AllowCredentials: true,
}))
app.Use(limiter.New(limiter.Config{
Max: 100,
Expiration: 1 * time.Minute,
}))
4. 内置中间件参考
| 中间件 | 用途 |
|---|---|
| logger | 请求日志 |
| recover | Panic 恢复 |
| cors | 跨域头 |
| limiter | 限流 |
| compress | Gzip/Brotli 压缩 |
| cache | 响应缓存 |
| helmet | 安全头 |
| csrf | CSRF 防护 |