首页 > 解决方案 > Kotlin Ktor API

问题描述

在我的学习中,我有一个使用 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!"))

有人可以帮助我吗?

谢谢

标签: kotlinktor

解决方案


在这种情况下,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
                )
            )
        }
    }

}

推荐阅读