kotlin-ktor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Kotlin Ktor Skill

Kotlin Ktor Skill

Build production-ready backends with Ktor.
使用Ktor构建可用于生产环境的后端。

Topics Covered

涵盖主题

Routing

路由

kotlin
fun Application.module() {
    install(ContentNegotiation) { json() }
    routing {
        route("/api/v1") {
            get("/users") { call.respond(userService.findAll()) }
            get("/users/{id}") {
                val id = call.parameters["id"]?.toLongOrNull()
                    ?: throw BadRequestException("Invalid ID")
                call.respond(userService.findById(id) ?: throw NotFoundException())
            }
        }
    }
}
kotlin
fun Application.module() {
    install(ContentNegotiation) { json() }
    routing {
        route("/api/v1") {
            get("/users") { call.respond(userService.findAll()) }
            get("/users/{id}") {
                val id = call.parameters["id"]?.toLongOrNull()
                    ?: throw BadRequestException("Invalid ID")
                call.respond(userService.findById(id) ?: throw NotFoundException())
            }
        }
    }
}

JWT Authentication

JWT身份验证

kotlin
install(Authentication) {
    jwt("auth") {
        verifier(JWT.require(Algorithm.HMAC256(secret)).build())
        validate { credential ->
            if (credential.payload.getClaim("userId").asString().isNotEmpty())
                UserPrincipal(credential.payload)
            else null
        }
    }
}

authenticate("auth") { userRoutes() }
kotlin
install(Authentication) {
    jwt("auth") {
        verifier(JWT.require(Algorithm.HMAC256(secret)).build())
        validate { credential ->
            if (credential.payload.getClaim("userId").asString().isNotEmpty())
                UserPrincipal(credential.payload)
            else null
        }
    }
}

authenticate("auth") { userRoutes() }

Testing

测试

kotlin
@Test
fun `GET users returns list`() = testApplication {
    application { module() }
    client.get("/api/v1/users").apply {
        assertThat(status).isEqualTo(HttpStatusCode.OK)
    }
}
kotlin
@Test
fun `GET users returns list`() = testApplication {
    application { module() }
    client.get("/api/v1/users").apply {
        assertThat(status).isEqualTo(HttpStatusCode.OK)
    }
}

Troubleshooting

故障排除

IssueResolution
404 for valid routeOrder specific routes before wildcards
JSON not parsedInstall ContentNegotiation plugin
问题解决方法
有效路由返回404将特定路由放在通配符路由之前
JSON无法解析安装ContentNegotiation插件

Usage

使用方法

Skill("kotlin-ktor")
Skill("kotlin-ktor")