【问题标题】:Kotlin Ktor APIKotlin Ktor API
【发布时间】:2019-08-13 00:07:32
【问题描述】:

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

有人可以帮我吗?

谢谢

【问题讨论】:

    标签: kotlin ktor


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我同意 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])
              }
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2018-11-22
        • 2021-03-29
        • 2020-10-14
        • 2021-09-12
        • 2018-03-09
        • 2019-12-21
        • 2019-12-08
        • 1970-01-01
        • 2022-07-06
        相关资源
        最近更新 更多