Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 访问Ktor中请求内的路由路径字符串_Kotlin_Ktor - Fatal编程技术网

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

Kotlin 访问Ktor中请求内的路由路径字符串,kotlin,ktor,Kotlin,Ktor,Ktor框架是否提供了在请求中访问路由路径字符串的方法 例如,如果我设置了一条路线,例如: routing { get("/user/{user_id}") { // possible to get the string "/user/{user_id}" here? } } 为了澄清这一点,我正在寻找一种访问未处理路径字符串的方法,即本例中的“/user/{user\u id}”(通过call.request.path()访问路径)在填写{user\u id

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

例如,如果我设置了一条路线,例如:

routing {
    get("/user/{user_id}") {
        // possible to get the string "/user/{user_id}" here?
    } 
}
为了澄清这一点,我正在寻找一种访问未处理路径字符串的方法,即本例中的
“/user/{user\u id}”
(通过
call.request.path()访问路径)在填写
{user\u id}
后给我路径,例如
“/user/123”


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

我认为这是不可能的。您可以改为编写这样的类/对象

object UserRoutes {

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

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

import package.UserRoutes

get(UserRoutes.userDetails) {...}
通过这样做,您只需要引用给定单例中的字符串。也不需要
对象
包装器,但我认为它看起来很整洁,您可以根据路径的模块名对路径进行分组

我这样解决了它

// 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")
}
为了构造我的扩展函数,我把它们放在像这样的其他文件中

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