🚀 Ktor 简介
📖 什么是 Ktor?
Ktor 是用 Kotlin 构建的轻量级异步 Web 框架。基于协程,可以轻松创建快速高效的服务器!
💡 创建项目
build.gradle.kts
plugins {
kotlin("jvm") version "1.9.0"
id("io.ktor.plugin") version "2.3.5"
}
dependencies {
implementation("io.ktor:ktor-server-core:2.3.5")
implementation("io.ktor:ktor-server-netty:2.3.5")
implementation("ch.qos.logback:logback-classic:1.4.11")
}
🎯 第一个服务器
Hello World
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun main() {
embeddedServer(Netty, port = 8080) {
routing {
get("/") {
call.respondText("Hello, Ktor!")
}
}
}.start(wait = true)
}
运行后在浏览器中访问 http://localhost:8080!
多个路由
fun main() {
embeddedServer(Netty, port = 8080) {
routing {
get("/") {
call.respondText("홈페이지")
}
get("/hello") {
call.respondText("안녕하세요!")
}
get("/about") {
call.respondText("소개 페이지")
}
}
}.start(wait = true)
}
🎨 路由
路径参数
fun Application.configureRouting() {
routing {
get("/user/{id}") {
val id = call.parameters["id"]
call.respondText("사용자 ID: $id")
}
get("/product/{category}/{id}") {
val category = call.parameters["category"]
val id = call.parameters["id"]
call.respondText("카테고리: $category, 상품 ID: $id")
}
}
}
fun main() {
embeddedServer(Netty, port = 8080) {
configureRouting()
}.start(wait = true)
}
// 접속: http://localhost:8080/user/123
// 출력: 사용자 ID: 123
查询参数
routing {
get("/search") {
val query = call.request.queryParameters["q"]
val page = call.request.queryParameters["page"]
call.respondText("검색어: $query, 페이지: $page")
}
}
// 접속: http://localhost:8080/search?q=kotlin&page=1
// 출력: 검색어: kotlin, 페이지: 1
🔧 JSON 响应
设置 ContentNegotiation
plugins {
// build.gradle.kts에 추가
implementation("io.ktor:ktor-server-content-negotiation:2.3.5")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.5")
}
JSON 响应
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.Serializable
@Serializable
data class User(val id: Int, val name: String, val email: String)
fun Application.module() {
install(ContentNegotiation) {
json()
}
routing {
get("/user/{id}") {
val id = call.parameters["id"]?.toInt() ?: 0
val user = User(id, "홍길동", "hong@example.com")
call.respond(user)
}
get("/users") {
val users = listOf(
User(1, "홍길동", "hong@example.com"),
User(2, "김철수", "kim@example.com")
)
call.respond(users)
}
}
}