Skip to content

Router

The Router is the core component of Fox, handling request routing and middleware.

Create a new router without any middleware:

r := fox.New()

Create a router with default middleware: response time header, request logger, and recovery.

r := fox.Default()
r.GET("/path", handler)
r.POST("/path", handler)
r.PUT("/path", handler)
r.DELETE("/path", handler)
r.PATCH("/path", handler)
r.HEAD("/path", handler)
r.OPTIONS("/path", handler)

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)
}

Fox route handlers can use these signatures:

func()
func(ctx *fox.Context) T
func(ctx *fox.Context) (T, error)
func(ctx *fox.Context, req Request) T
func(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.

Route based on domain names:

de := fox.NewDomainEngine()
// Exact domain
de.Domain("api.example.com", func(api *fox.Engine) {
api.GET("/users", handler)
})
// Regex domain
de.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"
})
// Global middleware
r.Use(middleware1(), middleware2())
// Group middleware
api := r.Group("/api")
api.Use(authMiddleware())
// Logger middleware
r.Use(fox.Logger())
// Response time header middleware
r.Use(fox.NewXResponseTimer())
// Recovery middleware
r.Use(fox.Recovery())
r.Run(":8080")
r.RunTLS(":8443", "cert.pem", "key.pem")
server := &http.Server{
Addr: ":8080",
Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
server.ListenAndServe()

fox.New() does not accept option arguments. Configure the embedded Gin engine and Fox fields directly:

r := fox.New()
r.MaxMultipartMemory = 32 << 20
r.SetTrustedProxies([]string{"127.0.0.1"})
r.DefaultRenderErrorStatusCode = http.StatusUnprocessableEntity