Routing
HttpFunction
Every route is a class or object that extends HttpFunction:
abstract class HttpFunction(
path: String,
httpMethod: HttpMethod,
middlewares: List<HttpFunctionMiddleware> = listOf()
)
| Parameter | Description |
|---|---|
path |
The path pattern for this route (see Path Patterns) |
httpMethod |
The HTTP method (HttpMethod.Get, .Post, .Put, .Patch, .Delete, etc.) |
middlewares |
Middlewares scoped to this route, running after defaultMiddlewares |
HttpFunctionRouter
The router matches an incoming request against all registered functions and dispatches it through the middleware pipeline.
class HttpFunctionRouter(
functions: List<HttpFunction>,
onError: (Throwable) -> Unit = {},
defaultMiddlewares: List<HttpFunctionMiddleware> = listOf(),
preRoutingMiddlewares: List<HttpFunctionMiddleware> = listOf()
)
Middleware pipeline
Requests flow through three layers in order:
preRoutingMiddlewares Runs before route matching (e.g. CORS, logging)
↓
[route matched]
↓
defaultMiddlewares Runs for every matched function (e.g. authentication)
↓
function.middlewares Per-route middleware
↓
handleRequest()
Error handling
| Scenario | Status Code |
|---|---|
Middleware calls halt(statusCode) |
The given status code |
| No route matches the request | 404 Not Found |
Unhandled exception in handleRequest |
500 Internal Server Error |
The onError callback fires on every failure — use it for centralized logging:
HttpFunctionRouter(
functions = listOf(...),
onError = { throwable -> logger.error("Request failed", throwable) }
)
Path Patterns
KRoute supports a rich path pattern syntax for matching and extracting values from URIs.
Literals
Exact segment match.
Named parameters {name}
Matches a single path segment and binds it to a name.
Single wildcard *
Matches any single segment without binding it to a name.
Path wildcard **
Matches one or more segments.
Multiple parameters
Custom verb {id}:verb
Matches a resource action in the style of Google AIP.
Complex ID {a}~{b}
Matches compound identifiers separated by a delimiter.
Specificity-based routing
When multiple patterns match the same request, KRoute automatically selects the most specific one — regardless of the registration order.
Each pattern has a specificity score:
| Segment type | Score |
|---|---|
| Literal | +10 |
Named parameter {id} |
+3 |
Path wildcard ** |
+0 |
Example:
/users/admin score 20 ← wins for GET /users/admin
/users/{id} score 13
/users/** score 10
/** score 0 ← catch-all fallback
Note
In case of a tie, the registration order is used as a tiebreaker.