Fiber框架指南
快速入门
go get github.com/gofiber/fiber/v2
package main
import "github.com/gofiber/fiber/v2"
func main() {
app := fiber.New(fiber.Config{
AppName: "MyAPI",
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
})
app.Get("/", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"message": "你好,世界!"})
})
app.Get("/users/:id", getUser)
app.Post("/users", createUser)
app.Put("/users/:id", updateUser)
app.Delete("/users/:id", deleteUser)
app.Listen(":8080")
}
中间件
import (
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/limiter"
)
app.Use(recover.New())
app.Use(logger.New())
app.Use(cors.New(cors.Config{
AllowOrigins: "https://example.com",
AllowMethods: "GET,POST,PUT,DELETE",
}))
app.Use(limiter.New(limiter.Config{
Max: 100,
Expiration: 1 * time.Minute,
}))
// 自定义中间件
app.Use(func(c *fiber.Ctx) error {
c.Set("X-Request-ID", uuid.New().String())
return c.Next()
})
Context 方法
| 方法 | 用途 |
|---|---|
| c.Params("id") | URL路径参数 |
| c.Query("page") | 查询字符串参数 |
| c.BodyParser(&dto) | 解析请求体 |
| c.JSON(data) | JSON 响应 |
| c.Status(404).JSON(...) | 状态码+JSON |
| c.Redirect("/path") | 重定向 |
| c.Locals("key", val) | 存储请求范围数据 |
| c.Get("X-Header") | 获取请求头 |