对于我的研究,我有一个使用Kotlin和Ktor开发的小API。目标是在启动应用程序时显示JSON信息。当我们的web浏览器中有http://127.0.0.1:8080/course/{id}时,应该会看到这些信息。id是某个课程id,如果id不同于浏览器上显示的错误消息,则id只能是egal到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不是egal到1,2,3.如果我有http://127.0.0.1:8080/course/4例如,我有一个错误说,该网站的网页是无效的.我想要展示的是:
call.respond(mapOf("status" to "404", "message: no course found!"))有人能帮帮我吗?
谢谢
发布于 2019-03-22 14:41:30
在这种情况下,Ktor已经响应为"404 not found“。
但是,如果您希望添加自己的消息,请删除for循环并将其替换为URL参数。
如果找不到课程id,则创建您自己的响应。
routing {
// .....
get("/course/{courseId}") {
val i = call.parameters["courseId"]!!.toInt() - 1
if (i < 0 || i >= courses.size) {
call.respond(HttpStatusCode.NotFound, "no course found!")
} else {
call.respond(
mapOf(
"id" to courses[i].id,
"title" to courses[i].title,
"level" to courses[i].level,
"isActive" to courses[i].isActive
)
)
}
}
}发布于 2019-04-23 02:37:20
我同意Egger的回答,但我不认为如果要简单地将整个对象转换为JSON,就不需要指定映射字段。您可以只使用对象本身进行响应,并让Ktor处理它。
routing {
// .....
get("/course/{courseId}") {
val i = call.parameters["courseId"]!!.toInt() - 1
if (i < 0 || i >= courses.size) {
call.respond(HttpStatusCode.NotFound, "no course found!")
} else {
call.respond(courses[i])
}
}
}https://stackoverflow.com/questions/55292244
复制相似问题