在 Ktor 中访问请求中的路由路径字符串

Accessing routing path string within request in Ktor

Ktor 框架是否提供了一种在请求中访问路由路径字符串的方法?

例如,如果我设置这样的路由:

routing {
    get("/user/{user_id}") {
        // possible to get the string "/user/{user_id}" here?
    } 
}

为了澄清,我正在寻找一种方法来访问未处理的路径字符串,即在这种情况下为 "/user/{user_id}"(通过 call.request.path() 访问路径为我提供了 [=13 之后的路径=] 已填写,例如 "/user/123").

我当然可以将路径分配给一个变量并将其传递给两者 get 并在函数体内使用它,但想知道是否有一种方法可以在不这样做的情况下到达路线的路径。

我认为这是不可能的。你可以做的是写这样一个 class/object

object UserRoutes {

    const val userDetails = "/users/{user_id}"
    ...

}

并从您的路由模块中引用该字段:

import package.UserRoutes

get(UserRoutes.userDetails) {...}

通过这样做,您只需要从给定的单例中引用该字符串。也不需要 object 包装器,但我认为您可以按 有点 它们的模块名称

对路径进行分组,这看起来很整洁

我是这样解决的

// Application.kt

private object Paths {
    const val LOGIN = "/login"
    ...
}

fun Application.module(testing: Boolean = false) {
    ...
    routing {
       loginGet(Paths.LOGIN)
    }
}

为了构造我的扩展函数,我将它们放在其他文件中,就像这样

// Auth.kt

fun Route.loginGet(path: String) = get(path) {
    println("The path is: $path")
}

我找到了这个问题的解决方案

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")
}

试试这个代码吧,它既简单又健壮

确实可以,也很简单

当您尝试访问/[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)
              }
            }
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()
        }
    }