Fiber 毕设实战 — Express 用户迁移到 Go 的最短路径

知识库
知识库文档
/tech-stacks/fiber/tutorial/Fiber 毕设实战 — Express 用户迁移到 Go 的最短路径.md

文档

Fiber 毕设实战 — Express 用户迁移到 Go 的最短路径

前言

Fiber 是 Go 生态中长得最像 Express 的框架。如果你熟悉 JavaScript/Express,Fiber 能让你在几小时内上手 Go 后端开发,同时享受 Go 的极致性能。

第一章:Fiber 与 Express 的对应关系

Express Fiber
const app = express() app := fiber.New()
app.use(middleware) app.Use(middleware)
app.get('/path', handler) app.Get("/path", handler)
req.params.id c.Params("id")
req.query.q c.Query("q")
req.body c.Body()
res.json(obj) c.JSON(obj)
res.status(404).send() c.Status(404).SendString("")
next() c.Next()

API 几乎一一对应,迁移成本极低。

第二章:Fiber 的 Context 方法大全

func handler(c fiber.Ctx) error {
    // 获取路径参数
    id := c.Params("id")

    // 获取查询参数
    page := c.Query("page", "1")

    // 获取请求头
    token := c.Get("Authorization")

    // 解析 JSON Body
    var body map[string]any
    c.Bind().JSON(&body)

    // 解析 Form
    name := c.FormValue("name")

    // 返回 JSON
    return c.JSON(fiber.Map{
        "id":   id,
        "page": page,
    })

    // 返回文件
    // return c.SendFile("./report.pdf")

    // 重定向
    // return c.Redirect("/new-url", 301)
}

第三章:Fiber 的钩子(Hooks)

Fiber v3 引入了钩子系统,可以在请求生命周期的特定阶段执行逻辑:

app := fiber.New()

// Hooks
app.Hooks().OnListen(func(listenData fiber.ListenData) error {
    log.Printf("🚀 服务已启动在 %s", listenData.Addr)
    return nil
})

app.Hooks().OnRoute(func(route fiber.Route) error {
    log.Printf("📝 注册路由: %s %s", route.Method, route.Path)
    return nil
})

第四章:Fiber + GORM 实战

type Product struct {
    ID    uint    `gorm:"primaryKey" json:"id"`
    Name  string  `json:"name"`
    Price float64 `json:"price"`
    Stock int     `json:"stock"`
}

func main() {
    db, _ := gorm.Open(sqlite.Open("shop.db"), &gorm.Config{})
    db.AutoMigrate(&Product{})

    app := fiber.New()

    app.Get("/products", func(c fiber.Ctx) error {
        var products []Product
        db.Find(&products)
        return c.JSON(products)
    })

    app.Post("/products", func(c fiber.Ctx) error {
        var p Product
        c.Bind().JSON(&p)
        db.Create(&p)
        return c.Status(201).JSON(p)
    })

    app.Listen(":3000")
}

第五章:Fiber 性能调优

app := fiber.New(fiber.Config{
    // 提高并发
    Prefork:       true,   // 多进程模式
    CaseSensitive: true,   // 路由区分大小写
    StrictRouting: false,  // /foo 和 /foo/ 视为相同

    // 压缩
    EnableTrustedProxyCheck: true,

    // 限制请求体大小(防攻击)
    BodyLimit: 10 * 1024 * 1024, // 10MB
})

Prefork: true 会让 Fiber fork 多个子进程(数量等于 CPU 核心数),每个子进程独立监听同一端口(SO_REUSEPORT),性能接近 Nginx。

思考题

  1. Fiber 的 Prefork 模式与 Node.js PM2 Cluster 有什么区别?
  2. Fiber 基于 fasthttp,而 fasthttp 不兼容 net/http 接口,这带来什么利弊?
  3. 在什么场景下应该选择 Fiber 而不是 Gin?

信息

路径
/tech-stacks/fiber/tutorial/Fiber 毕设实战 — Express 用户迁移到 Go 的最短路径.md
更新时间
2026/5/30