Request extensions
Request.pathOrNull()
Returns the value of a path variable of the route this request matched, or null when there is none to
read. Use it from a filter wrapping a whole route group, which runs before the leaf route binds its path
lens: http4k attaches the uri template outside the group's filters, so the variable is already readable
there.
Null covers every way the answer can be absent. The same filter also sees the requests that matched no
route (a 404) or matched the path with the wrong method (a 405), and those carry no uri template at all;
http4k's own Request.path(name) throws on them, which would turn a 404 into a 500. A value that matched
nothing but whitespace is null too.
- Example
- Declaration
val suspendedGate = Filter { next ->
{ request ->
val projectId = request.pathOrNull("projectId")
// ...
next(request)
}
}
suspendedGate.then(
routes(
"/projects/{projectId}" GET { /* ... */ },
"/projects/{projectId}/settings" GET { /* ... */ }
)
)
fun Request.pathOrNull(name: String): String?
Request.pathWithQuery()
The request's path with its query string appended when it has one, the part of the URL to hand back to a browser as a relative destination.
- Example
- Declaration
// GET /search?q=blue
request.pathWithQuery() // "/search?q=blue"
fun Request.pathWithQuery(): String
Request.sort()
Returns a Sort object from the query parameter sort in this request or null if this parameter is not present.
This should be in the form sort=<field>:<order>, for example sort=name:Asc, sort=createdAt:DESC. The order element
is not case-sensitive.
- Example
- Declaration
val sort = request.sort()
fun Request.sort(): Sort?
Request.page()
Returns a Page object from the query parameters from and size,
or a Page with the values from the default arguments when one or both these parameters are missing (see Declaration below).
The size is capped at maxSize, and a size below 1 falls back to defaultSize. from is at least 0 and
aligned down to a multiple of the size, as Page requires, so an offset written for another page size
(?from=30 on a listing of 20 per page) returns the page that holds it.
- Example
- Declaration
val page = request.page()
fun Request.page(
defaultFrom: Int = 0,
defaultSize: Int = 10,
maxSize: Int = defaultSize
): Page