Loading...
Loading...
Compare original and translation side by side
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())
}
}
}
}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())
}
}
}
}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() }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() }@Test
fun `GET users returns list`() = testApplication {
application { module() }
client.get("/api/v1/users").apply {
assertThat(status).isEqualTo(HttpStatusCode.OK)
}
}@Test
fun `GET users returns list`() = testApplication {
application { module() }
client.get("/api/v1/users").apply {
assertThat(status).isEqualTo(HttpStatusCode.OK)
}
}| Issue | Resolution |
|---|---|
| 404 for valid route | Order specific routes before wildcards |
| JSON not parsed | Install ContentNegotiation plugin |
| 问题 | 解决方法 |
|---|---|
| 有效路由返回404 | 将特定路由放在通配符路由之前 |
| JSON无法解析 | 安装ContentNegotiation插件 |
Skill("kotlin-ktor")Skill("kotlin-ktor")