You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ktor框架中能否在请求内获取路由的原始路径字符串?

How to Get the Raw Route Template String in Ktor

Absolutely, you don't have to store the route path in a variable to reuse it—Ktor provides a way to fetch the original, unprocessed route template directly within your handler. Here's how to do it:

Step 1: Access the Current Route via call.route

Ktor's ApplicationCall has a route property that gives you the Route instance matching the incoming request. This object holds all metadata about the route you defined, including its raw template.

Step 2: Fetch the Full Route Template

The Route class has a path property that returns the template segment for that specific route. If you have nested routes (like /api/user/{user_id}), you'll need to recursively combine path segments from parent routes to get the complete template.

Here's a reusable extension function to handle both flat and nested routes:

import io.ktor.server.routing.*

// Extension function to get the full raw route template
fun Route.fullRouteTemplate(): String {
    val parentTemplate = parent?.fullRouteTemplate().orEmpty()
    return parentTemplate + path
}

Step 3: Use It in Your Handler

Now you can call this function within your route handler to get the exact template you defined:

routing {
    get("/user/{user_id}") {
        val rawTemplate = call.route?.fullRouteTemplate()
        // Verify the template matches what we defined
        assert(rawTemplate == "/user/{user_id}")
    }

    // Example with nested routes
    route("/api") {
        get("/posts/{post_id}") {
            val fullRawTemplate = call.route?.fullRouteTemplate()
            assert(fullRawTemplate == "/api/posts/{post_id}")
        }
    }
}

Key Notes:

  • Always handle the nullable call.route value (it could be null if the request didn't match any defined route).
  • The path property returns the exact template string you used when defining the route—no filled-in parameters (like /user/123) will be included.

This approach keeps your code clean and avoids duplicating route path strings across your codebase.

内容的提问来源于stack exchange,提问作者Dave Challis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:42:47