Skip to content

Routing ​

Added: v1.0.0

Zen uses a custom per-method radix tree router. It provides :param and *param wildcard segments (or {param} / {path...} syntax which is auto-converted), trailing-slash redirect, HEAD fallback, 405 detection, and zero allocations on all routing paths.

Basic Routes ​

Register handlers with HTTP method and path:

go
r.GET("/users", listUsers)
r.GET("/users/:id", getUser)
r.POST("/users", createUser)
r.PUT("/users/:id", updateUser)
r.DELETE("/users/:id", deleteUser)

You may also use Go ServeMux-style {param} syntax - it is converted to :param automatically:

go
r.GET("/users/{id}", getUser)   // same as r.GET("/users/:id", getUser)
r.HandleRaw("GET /static/{path...}", fileHandler) // same as /*path

Path Parameters ​

Access path parameters via c.Param("name"):

go
r.GET("/users/:id", func(c *zen.Ctx) {
    id := c.Param("id")
    c.String(200, "User: "+id)
})

Multiple parameters work naturally:

go
r.GET("/posts/:year/:month/:slug", func(c *zen.Ctx) {
    year  := c.Param("year")
    month := c.Param("month")
    slug  := c.Param("slug")
    c.JSON(200, map[string]string{"year": year, "month": month, "slug": slug})
})

Path parameters are URL-decoded automatically (%2F → /, %C3%A9 → é).

Get all path params as a map:

go
r.GET("/posts/:year/:month/:slug", func(c *zen.Ctx) {
    all := c.Params()  // map[string]string{"year": "2024", "month": "01", "slug": "hello"}
})

Use a fallback default when the parameter is missing:

go
slug := c.DefaultParam("slug", "index") // "index" if :slug is absent or empty

Catch-All (Wildcard) Routes ​

Use *param (or {param...}) to match everything after the prefix:

go
r.GET("/static/*path", func(c *zen.Ctx) {
    filePath := c.Param("path") // "css/style.css" for /static/css/style.css
})

Catch-all routes must be the final segment. The leading / is stripped from the captured value (matching Go ServeMux behavior).

Trailing Slash Redirect ​

When a registered path does not have a trailing slash but the request does (or vice versa), the router returns a 301 redirect automatically:

go
r.GET("/users", handler)   // GET /users/ → 301 → /users
r.GET("/admin/", handler)  // GET /admin  → 301 → /admin/

HEAD Fallback ​

If no explicit HEAD route is registered, the router falls back to the GET handler automatically. An explicit HEAD route takes priority:

go
r.GET("/users", listUsers)           // HEAD /users → falls back to listUsers
r.HEAD("/users", headOnlyHandler)    // HEAD /users → uses headOnlyHandler instead

Method Not Allowed ​

When a path matches a route for a different HTTP method, the router returns a 405 response with an Allow header listing the available methods:

go
r.GET("/resource", getHandler)
r.POST("/resource", postHandler)

// PUT /resource → 405, Allow: GET, POST

Serving Static Files ​

go
r.File("/", "public/index.html")             // single file
r.Static("/images", "assets/images")         // directory
r.StaticFS("/assets", assetsFS)              // embed.FS

Query Parameters ​

Query parameters are accessed via the standard Request.URL.Query():

go
r.GET("/search", func(c *zen.Ctx) {
    q     := c.Request.URL.Query().Get("q")
    page  := c.Request.URL.Query().Get("page")
    c.String(200, "Search: "+q)
})

Or use c.QueryParam("key") for convenience:

go
q := c.QueryParam("q")

Get all query params as a map:

go
params := c.QueryParams()  // map[string][]string
vals   := params["tags"]   // ["go", "zen"]

Use a fallback default when the parameter is missing:

go
page := c.DefaultQuery("page", "1") // "1" if ?page is absent or empty

Request Headers ​

Access request headers via c.Header("Key"):

go
r.GET("/protected", func(c *zen.Ctx) {
    token := c.Header("Authorization")
    if token == "" {
        c.Error(401, "missing token")
        return
    }
    c.String(200, "authorized")
})

Request Inspection ​

go
// Check if request is an AJAX call
if c.IsAjax() {
    // Return JSON instead of full HTML
}

// Get parsed MIME content type
ct := c.ContentType() // "application/json", "text/html", etc.

// Get the client IP address
ip := c.ClientIP()    // checks X-Forwarded-For, X-Real-IP, then RemoteAddr

Released under the MIT License.