glimr/routing/router


Router

Pattern matching router with prefix-based route groups for organizing routes with shared middleware. Provides type-safe parameter extraction and lazy loading of route handlers based on URL prefix matching.

Types


RouteGroup Type

Groups routes together with a shared middleware group and handler function. Routes use pattern matching for type-safe parameter extraction. The prefix field enables efficient route matching and lazy loading of route modules.

pub type RouteGroup(context) {
  RouteGroup(
    prefix: String,
    middleware_group: kernel.MiddlewareGroup,
    routes: fn(
      List(String),
      http.Method,
      request.Request(wisp.Connection),
      context,
    ) -> response.Response(wisp.Body),
  )
}

Constructors

Values

pub fn handle(
  req: request.Request(wisp.Connection),
  ctx: ctx,
  route_groups: List(RouteGroup(ctx)),
  kernel_handle: fn(
    request.Request(wisp.Connection),
    ctx,
    kernel.MiddlewareGroup,
    fn(request.Request(wisp.Connection)) -> response.Response(
      wisp.Body,
    ),
  ) -> response.Response(wisp.Body),
) -> response.Response(wisp.Body)

Handle Request

Main entry point for routing HTTP requests. Matches the request path against registered route groups, strips the prefix, applies middleware, and calls the route handler.

Route groups are checked in order. The first matching prefix wins. Empty prefix (“”) acts as a catch-all and should always be last in your route group list.

Flow for GET /api/users/123:

  1. Parse path into [“api”, “users”, “123”]
  2. Find group with prefix “/api”
  3. Strip prefix → [“users”, “123”]
  4. Apply API middleware group
  5. Call routes([“users”, “123”], Get, req, ctx)
pub fn match(
  method: http.Method,
  handlers: List(
    #(http.Method, fn() -> response.Response(wisp.Body)),
  ),
) -> response.Response(wisp.Body)

Handle Methods

Helper for matching HTTP methods to handlers within a route. Returns 405 Method Not Allowed if the method doesn’t match any of the provided handlers. Uses lazy evaluation through functions to avoid executing all handlers.

This allows grouping handlers by path, separating path matching from method matching for cleaner route definitions.


Example:

pub fn routes(path, method, req, ctx) {
  case path {
    ["users"] ->
      router.match(method, [
        #(Get, fn() { user_controller.index(req, ctx) }),
        #(Post, fn() { user_controller.create(req, ctx) }),
      ])

    _ -> wisp.response(404)
  }
}
Search Document