Skip to content

Routing

Thiago Santos edited this page Aug 13, 2024 · 3 revisions

Define a route handler

Based on Ktor Routing

All route definition provided by Ktor Routing is supported by Kotlin Routing.

val router = routing {
    handle("/hello") {
        // Handle any call to the "/hello" route
    }
}

It's also possible to define a name to navigate instead of using the path value.

route(path = "/hello", name = "hello") {
    // ...
}

Route Method

Well, there is no Get, Post and no other HttpMethod related verb functions, of course.

So to distinguish some route from another you can create or use the default route methods.

val router = routing {
    handle("/hello", method = RouteMethod("PUSH")) {
        // Handle any call to the "/hello" route
    }
}

Specify a path pattern

The same as oficial docs Specify a path pattern

Define multiple route handlers

Define routes by paths

If you want to define multiple route handlers, which of course is the case for any application, you can just add them to the routing function:

val router = routing {
    handle("/customer/{id}") {
        // ...
    }
    handle("/customer") {
        // ...
    }
    handle("/order") {
        // ...
    }
    handle("/order/{id}") {
        // ...
    }
}

In this case, each route has its own function and responds to the specific route.

Group routes by paths

An alternative way is to group these by paths, whereby you define the path and then place the handle for that path as nested functions, using the route function:

val router = routing {
    route("/customer") {
        handle {
            // handle call to /customer
        }

        handle("/{id}") {
            // handle call to /customer/id
        }
    }
    route("/order") {
        handle {
            // handle call to /order
        }

        handle("/{id}") {
            // handle call to /order/id
        }
    }
}

Nested routes

Kotlin Routing allows you to have sub-routes as parameters to route functions. This can be useful to define resources that are logically children of other resources.

val router = routing {
    route("/order") {
        route("/shipment") {
            handle {
                // handle call to /order/shipment
            }

            handle("/{id}") {
                // handle call to /order/shipment/id
            }
        }
    }
}

Route extension functions

The same as oficial docs Route extension functions

Clone this wiki locally