在我的学习中,我有一个使用 Kotlin 和 Ktor 开发的小型 API。目标是在启动应用程序时显示 JSON 信息。当我们的网络浏览器中有http://127.0.0.1:8080/course/ {id} 时,应该可以看到这些信息。id 是一些课程 id,如果 id 与浏览器上显示的错误消息不同,则只能等于 1、2、3。
我今天的代码是
fun main(args: Array<String>): Unit =
io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
install(ContentNegotiation) {
jackson {
enable(SerializationFeature.INDENT_OUTPUT)
}
}
routing {
get("/") {
call.respondText("Welcome to OpenClassrooms brand new server !", contentType = ContentType.Text.Plain)
}
get("/course/top") {
call.respond(mapOf("id" to courses[0].id, "title" to courses[0].title, "level" to courses[0].level, "isActive" to courses[0].isActive))
}
for (i in 0..2){
get("/course/${i.addOneToInt()}") {
call.respond(mapOf("id" to courses[i].id, "title" to courses[i].title, "level" to courses[i].level, "isActive" to courses[i].isActive))
}
}
}
}
data class Course(val id: Int, val title: String, val level: Int, val isActive: Boolean)
val courses = Collections.synchronizedList(listOf(
Course(1, "How to troll a Troll?",5,true),
Course(2, "Kotlin for Troll",1,true),
Course(3, "Kotlin vs Java",3,true))
)
我对 kotlin 和 ktor 不是很友好。该应用程序目前正在运行,但是当 id 不等于 1、2、3 时,我不知道如何覆盖错误消息。如果我有http://127.0.0.1:8080/course/4例如我有一个错误说网站页面无效。我想改为显示:
call.respond(mapOf("status" to "404", "message: no course found!"))
有人可以帮助我吗?
谢谢