文档
Fiber 快速入门 — 用户管理 API
目标
使用 Fiber 的 Express 风格 API 快速搭建用户 CRUD,演示路由、中间件、参数解析。
完整代码
package main
import (
"log"
"strconv"
"time"
"github.com/gofiber/fiber/v3"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Role string `json:"role"`
CreatedAt time.Time `json:"createdAt"`
}
var (
users = []User{}
nextID = 1
)
func main() {
app := fiber.New()
// 全局日志中间件
app.Use(func(c fiber.Ctx) error {
start := time.Now()
err := c.Next()
log.Printf("[%s] %s — %v", c.Method(), c.Path(), time.Since(start))
return err
})
// 用户路由组
api := app.Group("/api")
api.Get("/users", func(c fiber.Ctx) error {
return c.JSON(fiber.Map{"count": len(users), "data": users})
})
api.Get("/users/:id", func(c fiber.Ctx) error {
id, _ := strconv.Atoi(c.Params("id"))
for _, u := range users {
if u.ID == id {
return c.JSON(u)
}
}
return c.Status(404).JSON(fiber.Map{"error": "用户不存在"})
})
api.Post("/users", func(c fiber.Ctx) error {
user := new(User)
if err := c.Bind().JSON(user); err != nil {
return c.Status(400).JSON(fiber.Map{"error": "JSON 解析失败"})
}
if user.Name == "" || user.Email == "" {
return c.Status(400).JSON(fiber.Map{"error": "姓名和邮箱为必填"})
}
user.ID = nextID
nextID++
user.CreatedAt = time.Now()
users = append(users, *user)
return c.Status(201).JSON(user)
})
api.Put("/users/:id", func(c fiber.Ctx) error {
id, _ := strconv.Atoi(c.Params("id"))
for i, u := range users {
if u.ID == id {
var update User
if err := c.Bind().JSON(&update); err != nil {
return c.Status(400).JSON(fiber.Map{"error": "JSON 解析失败"})
}
if update.Name != "" {
users[i].Name = update.Name
}
if update.Email != "" {
users[i].Email = update.Email
}
if update.Role != "" {
users[i].Role = update.Role
}
return c.JSON(users[i])
}
}
return c.Status(404).JSON(fiber.Map{"error": "用户不存在"})
})
api.Delete("/users/:id", func(c fiber.Ctx) error {
id, _ := strconv.Atoi(c.Params("id"))
for i, u := range users {
if u.ID == id {
users = append(users[:i], users[i+1:]...)
return c.JSON(fiber.Map{"message": "已删除"})
}
}
return c.Status(404).JSON(fiber.Map{"error": "用户不存在"})
})
log.Fatal(app.Listen(":3000"))
}
运行步骤
go mod init fiber-demo
go get github.com/gofiber/fiber/v3
go run main.go
测试
# 新增
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name":"李四","email":"lisi@qq.com","role":"student"}'
# 获取
curl http://localhost:3000/api/users
# 更新
curl -X PUT http://localhost:3000/api/users/1 \
-H "Content-Type: application/json" \
-d '{"role":"admin"}'
# 删除
curl -X DELETE http://localhost:3000/api/users/1
预期输出
- 所有请求自动打印日志:
[GET] /api/users — 1.2ms - Fiber v3 使用
c.Bind().JSON()替代旧版c.BodyParser() - 响应头自动带
Server: Fiber