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.routevalue (it could benullif the request didn't match any defined route). - The
pathproperty 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

