路由器
路由器 API
Section titled “路由器 API”路由器是 Fox 的核心组件,处理请求路由和中间件。
fox.New()
Section titled “fox.New()”创建一个没有任何中间件的新路由器:
r := fox.New()fox.Default()
Section titled “fox.Default()”创建一个带有默认中间件(Logger 和 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)}基于域名的路由:
// 精确域名r.Domain("api.example.com").GET("/users", handler)
// 通配符r.Domain("*.example.com").GET("/info", handler)
// 正则表达式r.DomainRegex(`^([a-z]+)\.example\.com$`).GET("/", handler)// 全局中间件r.Use(middleware1(), middleware2())
// 组中间件api := r.Group("/api")api.Use(authMiddleware())import "github.com/fox-gonic/fox/middleware"
// 日志中间件r.Use(middleware.Logger())
// 恢复中间件r.Use(middleware.Recovery())
// CORS 中间件r.Use(middleware.CORS())在端口上运行
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()使用选项创建路由器
Section titled “使用选项创建路由器”r := fox.New( fox.WithLoggerConfig(loggerConfig), fox.WithMaxMemory(32 << 20), // 32 MB fox.WithTrustedProxies([]string{"127.0.0.1"}),)- Context API - 使用请求上下文
- 中间件指南 - 创建自定义中间件