1. 入门
1 | go get github.com/gofiber/fiber/v2 |
编写主函数:
1 | func main() { |
2. 配置
1 | func main() { |
3. 路由
3.1 参数
1 | func main() { |
3.2 Add & All
Fiber 路由支持额外的方法:
Add:所有 HTTP Method 对应的底层实现
1
2
3
4// Fiber 自动添加 Head 方法
func (app *App) Get(path string, handlers ...Handler) Router {
return app.Add(MethodHead, path, handlers...).Add(MethodGet, path, handlers...)
}All:支持任意的 HTTP Method 请求
3.3 Mount & Group
Mount: 可以将一个 Fiber 实例挂载到另一个实例
1 | func main() { |
Group: 路由分组
1 | func calc(c *fiber.Ctx) error { |
4. 静态资源
1 | app.Static("/images", `/data/images`, fiber.Static{Browse: true}) |
5. 使用模板
pug 模板: index.pug
1 | html |
解析:
1 | func main() { |
6. fiber.Ctx
方法
6.1 c.BodyParser
1 | type User struct { |
测试:
1 | curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"pass\":\"doe\"}" localhost:3000/login |
6.2 c.Query()
1 | func main() { |
7. 中间件
7.1 自定义
1 | app.Use(func(c *fiber.Ctx) error { |
7.2 内置中间件
https://docs.gofiber.io/api/middleware
1 | func main() { |
7.2.1 签名
1 | func New(config ...Config) fiber.Handler |
7.2.2 配置
1 | type Config struct { |
7.3 自建中间件
1 | // 响应headers中设置如下参数 |
8. 单元测试
Fiber 提供专门的测试方法:
1 | // Test is used for internal debugging by passing a *http.Request. |
待测试程序:
1 | func setupRouters(app *fiber.App) { |
测试代码:
1 | func TestHelloRoute(t *testing.T) { |