Skip to main content

Uri Extensions

Kotlin extensions on org.http4k.core.Uri for the URI manipulation patterns common in server-rendered pages: filter chips, pagination links, sort headers, etc. The same operations are exposed on InvirtRequest for use inside Pebble templates.

hasQueryParam

fun Uri.hasQueryParam(name: String): Boolean

hasQueryValue

Checks whether the URI has a query parameter with the given name and value.

// true
Uri.of("/test?q=kotlin").hasQueryValue("q", "kotlin")

// false
Uri.of("/test?size=large").hasQueryValue("size", "small")

queryValue

Returns the first value of the named query parameter, case-insensitive on the parameter name.

fun Uri.queryValue(name: String): String?

removeQueryValue

Returns a new Uri without the specified name/value pair. All other query params are left unchanged.

// "/test"
Uri.of("/test?q=John").removeQueryValue("q", "John")

// "/test?q=kotlin"
Uri.of("/test?q=kotlin&q=java").removeQueryValue("q", "java")

toggleQueryValue

Returns a new Uri with the specified name/value pair added when not present, or removed when present. All other query params are left unchanged.

// "/test?q=John"
Uri.of("/test").toggleQueryValue("q", "John")

// "/test"
Uri.of("/test?q=John").toggleQueryValue("q", "John")

removeQueries

Removes all query parameters with the given names (regardless of value).

// "/test"
Uri.of("/test?q=john&filter=name").removeQueries(listOf("q", "filter"))

replaceQuery

Replaces the given query parameters with new values. All other query params are left unchanged.

// "/test?q=John&size=10"
Uri.of("/test?q=nothing&size=5").replaceQuery("q" to "John", "size" to "10")

replacePage

Returns a new Uri with the from/size pagination parameters replaced to match the given Page.

// "/test?from=10&size=5"
Uri.of("/test?from=0&size=10").replacePage(Page(10, 5))

replaceSort

Returns a new Uri with the sort query parameter replaced to match the given Sort. By default pagination (from/size) is reset; pass resetPagination = false to keep it.

// "/test?sort=createdAt:desc"
Uri.of("/test?sort=name:asc").replaceSort(Sort.desc("createdAt"))

CSV-encoded multi-value parameters

For situations where multiple values are encoded into a single comma-separated query parameter (?tags=red,green,blue), Invirt provides helpers to read and mutate the list:

// ["red", "green"]
Uri.of("/?tags=red,green").csvQuery("tags")

// "/?tags=red,green,blue"
Uri.of("/?tags=red,green").csvAppend("tags", "blue")

// "/?tags=red"
Uri.of("/?tags=red,green").csvRemove("tags", "green")

// Toggles: add if missing, remove if present
Uri.of("/?tags=red,green").csvToggle("tags", "blue")