【问题标题】:How to build nested routes in Ktor?如何在 Ktor 中构建嵌套路由?
【发布时间】:2022-01-16 23:57:32
【问题描述】:

我在单独的文件中定义了我的路线:

PostRoutes.kt:

fun Route.getPostsRoute() {
    get("/posts") {
        call.respondText("Posts")
    }
}

// Some other routes

fun Application.postRoutes() {
    routing {
        getPostsRoute()
        // Some other routes
    }
}

我在 Application.kt 中设置了这些路由,如下所示:

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

fun Application.module(testing: Boolean = false) {
    routing { // I want to provide the root endpoint (/api/v1) here
        postRoutes()
    }
}

在这种情况下如何设置我的根端点 (/api/v1)?

PS我检查了他们的文档,它说要使用嵌套的 routes,但我不能,因为我需要在 postRoutes() 中调用 routing,这会破坏嵌套路由。

P.P.S.我是 Ktor 和 Kotlin 的菜鸟。

【问题讨论】:

    标签: kotlin ktor


    【解决方案1】:

    您可以将getPostsRoute()route("/api/v1") 包装在postRoutes 方法中,或者去掉postRoutes 方法并将您的路由嵌套在routing {} 中。

    import io.ktor.application.*
    import io.ktor.response.*
    import io.ktor.routing.*
    import io.ktor.server.engine.*
    import io.ktor.server.netty.*
    
    fun main() {
        embeddedServer(Netty, port = 5555, host = "0.0.0.0") {
            postRoutes()
        }.start(wait = false)
    }
    
    fun Route.getPostsRoute() {
        get("/posts") {
            call.respondText("Posts")
        }
    }
    
    fun Application.postRoutes() {
        routing {
            route("/api/v1") {
                getPostsRoute()
            }
        }
    }
    

    【讨论】:

    • 感谢您的回答!是的,他们在他们的文档中提供了这个变体,但是当你有很多端点时它并不方便。如何为我的情况制作它?当我在许多文件中有许多路由并且每个文件都有一个入口点来设置其路由时。我不想为每个文件设置根路径,也不想在一个地方注册每个端点,这会很乱。
    • 您不必为每个文件设置根路径。只需在 入口方法 中定义任意数量的路由,例如 getPostsRoute,然后在集中式 routing 块内调用它。
    • 我怎样才能不在一个地方设置 getPosts、getTags、putPost 和 +100500 端点?我可以在根路径的一个地方只设置我的postRoutes'tagRoutes 等等,并且每个入口点都会设置它的路由吗?不幸的是,这对我的情况来说更方便
    • 是的,你可以。以这种方式定义它们有什么问题?
    猜你喜欢
    • 2016-05-08
    • 1970-01-01
    • 2022-08-17
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多