路由器
路由器是 Fox 的核心组件,处理请求路由和中间件。
fox.New()
Section titled “fox.New()”创建一个没有任何中间件的新路由器:
r := fox.New()fox.Default()
Section titled “fox.Default()”创建一个带有默认中间件的路由器:响应时间头、请求日志和 Recovery。
r := fox.Default()HTTP 方法
Section titled “HTTP 方法”r.GET("/path", handler)r.POST("/path", handler)r.PUT("/path", handler)DELETE
Section titled “DELETE”r.DELETE("/path", handler)r.PATCH("/path", handler)r.HEAD("/path", handler)OPTIONS
Section titled “OPTIONS”r.OPTIONS("/path", handler)创建具有共享前缀和中间件的路由组:
api := r.Group("/api")api.Use(authMiddleware()){ api.GET("/users", listUsers) api.POST("/users", createUser)}
v1 := api.Group("/v1"){ v1.GET("/products", listProducts)}Fox 路由处理器支持这些签名:
func()func(ctx *fox.Context) Tfunc(ctx *fox.Context) (T, error)func(ctx *fox.Context, req Request) Tfunc(ctx *fox.Context, req *Request) (T, error)如果有入参,第一个参数必须是 *fox.Context。第二个参数可以是结构体、结构体指针、map 或 interface,Fox 会从请求中自动绑定。
基于域名的路由:
de := fox.NewDomainEngine()
// 精确域名de.Domain("api.example.com", func(api *fox.Engine) { api.GET("/users", handler)})
// 正则域名de.DomainRegexp(`^([a-z]+)\.example\.com$`, func(app *fox.Engine) { app.GET("/", handler)})
// 回退路由注册在 DomainEngine 自身de.GET("/health", func() string { return "OK"})// 全局中间件r.Use(middleware1(), middleware2())
// 组中间件api := r.Group("/api")api.Use(authMiddleware())// 日志中间件r.Use(fox.Logger())
// 响应时间头中间件r.Use(fox.NewXResponseTimer())
// Recovery 中间件r.Use(fox.Recovery())在端口上运行
Section titled “在端口上运行”r.Run(":8080")使用 TLS 运行
Section titled “使用 TLS 运行”r.RunTLS(":8443", "cert.pem", "key.pem")使用自定义服务器运行
Section titled “使用自定义服务器运行”server := &http.Server{ Addr: ":8080", Handler: r, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second,}server.ListenAndServe()Engine 配置
Section titled “Engine 配置”fox.New() 不接收 option 参数。请直接配置嵌入的 Gin engine 和 Fox 字段:
r := fox.New()r.MaxMultipartMemory = 32 << 20r.SetTrustedProxies([]string{"127.0.0.1"})r.DefaultRenderErrorStatusCode = http.StatusUnprocessableEntity- Context API - 使用请求上下文
- 中间件指南 - 创建自定义中间件