Router
The Router is the core component of Fox, handling request routing and middleware.
Creating a Router
Section titled “Creating a Router”fox.New()
Section titled “fox.New()”Create a new router without any middleware:
r := fox.New()fox.Default()
Section titled “fox.Default()”Create a router with default middleware: response time header, request logger, and recovery.
r := fox.Default()HTTP Methods
Section titled “HTTP Methods”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)Route Groups
Section titled “Route Groups”Create route groups with shared prefix and middleware:
api := r.Group("/api")api.Use(authMiddleware()){ api.GET("/users", listUsers) api.POST("/users", createUser)}
v1 := api.Group("/v1"){ v1.GET("/products", listProducts)}Handler Signatures
Section titled “Handler Signatures”Fox route handlers can use these signatures:
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)The first argument, when present, must be *fox.Context. The second argument may be a struct, pointer to struct, map, or interface and is automatically bound from the request.
Domain Routing
Section titled “Domain Routing”Route based on domain names:
de := fox.NewDomainEngine()
// Exact domainde.Domain("api.example.com", func(api *fox.Engine) { api.GET("/users", handler)})
// Regex domainde.DomainRegexp(`^([a-z]+)\.example\.com$`, func(app *fox.Engine) { app.GET("/", handler)})
// Fallback routes live on the DomainEngine itself.de.GET("/health", func() string { return "OK"})Middleware
Section titled “Middleware”Use Middleware
Section titled “Use Middleware”// Global middlewarer.Use(middleware1(), middleware2())
// Group middlewareapi := r.Group("/api")api.Use(authMiddleware())Built-in Middleware
Section titled “Built-in Middleware”// Logger middlewarer.Use(fox.Logger())
// Response time header middlewarer.Use(fox.NewXResponseTimer())
// Recovery middlewarer.Use(fox.Recovery())Running the Server
Section titled “Running the Server”Run on Port
Section titled “Run on Port”r.Run(":8080")Run with TLS
Section titled “Run with TLS”r.RunTLS(":8443", "cert.pem", "key.pem")Run with Custom Server
Section titled “Run with Custom Server”server := &http.Server{ Addr: ":8080", Handler: r, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second,}server.ListenAndServe()Engine Configuration
Section titled “Engine Configuration”fox.New() does not accept option arguments. Configure the embedded Gin engine and Fox fields directly:
r := fox.New()r.MaxMultipartMemory = 32 << 20r.SetTrustedProxies([]string{"127.0.0.1"})r.DefaultRenderErrorStatusCode = http.StatusUnprocessableEntityNext Steps
Section titled “Next Steps”- Context API - Working with request context
- Middleware Guide - Creating custom middleware