Ktor框架指南
快速入门
// build.gradle.kts
dependencies {
implementation("io.ktor:ktor-server-core:2.3.0")
implementation("io.ktor:ktor-server-netty:2.3.0")
implementation("io.ktor:ktor-server-content-negotiation:2.3.0")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.0")
}
// Application.kt
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.routing.*
import io.ktor.server.response.*
import io.ktor.server.request.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(ContentNegotiation) { json() }
routing {
get("/users") { call.respond(listUsers()) }
get("/users/{id}") {
val id = call.parameters["id"]?.toInt() ?: return@get
call.respond(getUser(id))
}
post("/users") {
val user = call.receive<User>()
call.respond(HttpStatusCode.Created, createUser(user))
}
}
}.start(wait = true)
}
常用插件
| 插件 | 用途 |
|---|---|
| ContentNegotiation | JSON/XML序列化 |
| Authentication | JWT、Basic、OAuth |
| CORS | 跨域资源共享 |
| StatusPages | 错误处理 |
| Compression | Gzip/Deflate压缩 |
| Sessions | Cookie/Header会话 |
| WebSockets | WebSocket支持 |
| RateLimit | 请求速率限制 |