使用Ktor框架开发应用:模块化、数据库连接与并发处理
1. 应用模块化
在开发过程中,我们最初从 main() 函数启动服务器,这种方式简单但不利于测试。在Ktor中,代码通常按模块组织。下面是重写后的 main 函数:
fun main() {
embeddedServer(
CIO,
port = 8080,
module = Application::mainModule
).start(wait = true)
}
这里,我们指定了一个模块 Application::mainModule ,该模块包含服务器的所有配置。这个模块定义为 Application 对象的扩展函数:
fun Application.mainModule() {
install(ContentNegotiation) {
json()
}
routing {
get("/status") {
call.respond(mapOf("status" to "OK"))
}
}
println("open http://localhost:8080")
}
现在,我们可以在测试中指定要测试的模块:
超级会员免费看
订阅专栏 解锁全文
517

被折叠的 条评论
为什么被折叠?



