'Accessing routing path string within request in Ktor
Does the Ktor framework provide a way of accessing a route's path string within a request?
For example, if I set up a route such as:
routing {
get("/user/{user_id}") {
// possible to get the string "/user/{user_id}" here?
}
}
To clarify, I'm looking for a way to access the unprocessed path string, i.e. "/user/{user_id}" in this case (accessing the path via call.request.path() gives me the path after the {user_id} has been filled in, e.g. "/user/123").
I can of course assign the path to a variable and pass it to both get and use it within the function body, but wondering if there's a way of getting at the route's path without doing that.
Solution 1:[1]
I solved it like this
// Application.kt
private object Paths {
const val LOGIN = "/login"
...
}
fun Application.module(testing: Boolean = false) {
...
routing {
loginGet(Paths.LOGIN)
}
}
And to structure my extension functions, I put them in other files like this
// Auth.kt
fun Route.loginGet(path: String) = get(path) {
println("The path is: $path")
}
Solution 2:[2]
It is indeed possible and very simple.
when you try to access/[GET] URL: /users/7
you should get the full path -> "users/7"
routing {
get("/users/{user_id}") {
val userPath = call.request.path() // This should be your solution // Note: userPath holds "users/7"
call.respond(userPath)
}
}
Solution 3:[3]
fun Route.fullPath(): String {
val parentPath = parent?.fullPath()?.let { if (it.endsWith("/")) it else "$it/" } ?: "/"
return when (selector) {
is TrailingSlashRouteSelector,
is AuthenticationRouteSelector -> parentPath
else -> parentPath + selector.toString()
}
}
Solution 4:[4]
I found a solution for this problem
val uri = "foos/foo"
get("$uri/{foo_id}") {
val path = call.request.path()
val firstPart = path.length
val secondPart = path.slice((firstPart+1) until path.length)
call.respondText("$secondPart")
}
try this code it's simple and robust
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MisseMask |
| Solution 2 | Koch |
| Solution 3 | |
| Solution 4 | George Nady |
