【问题标题】:Is there a way to access the parameter used inside route() in ktor有没有办法访问 ktor 中 route() 中使用的参数
【发布时间】:2022-11-03 14:16:37
【问题描述】:

根据Ktor documentation,我们可以使用call.paramters["params"] 访问路由中的路径参数,如下所示,

get("/user/{login}") {
    if (call.parameters["login"] == "admin") {
        // ...
    }
}

但是,例如,当我们使用嵌套路由时,

routing {
    route("/order") {
        route("/shipment/{param1}") { 
               ----------need param1 here---------------
            get("/sample/{param2}") {

            }
            post("/sample/{param2}") {

            }
        }
    }
}

在这里,我们可以使用上述方法访问 param2 和 param3。 Param1 在 URL 中被视为字符串本身。有没有办法在访问 get 和 post 方法之前访问 param1(如代码中所述)?

【问题讨论】:

    标签: routes url-routing ktor


    【解决方案1】:

    您可以在get("/sample/{param2}")post("/sample/{param2}") 路由中同时访问param1param2。如果要在route("/shipment/{param1}") 路由中访问param1,则可以调用handle 方法或添加HTTP 方法路由:

    route("/shipment/{param1}") {
        get {
            println(call.parameters["param1"])
        }
    
        handle { // handles any HTTP method
            println(call.parameters["param1"])
        }
    
        // ...
    }
    

    【讨论】:

    【解决方案2】:

    您可以使用路由范围插件,它部分记录在 here 但这里是一个示例

    route("/order") {
                route("/shipment/{param1}") {
                    install(createRouteScopedPlugin("pluginName"){
                        on(CallSetup) { call ->
                            val param = call.parameters["param1"]
                        }
                    })
                    get("/sample/{param2}") {
    
                    }
                    post("/sample/{param2}") {
    
                    }
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2012-03-01
      • 2015-10-22
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多