推荐答案
// www.javascriptcn.com code example
import io.ktor.application.*
import io.ktor.features.ContentNegotiation
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.serialization.json.*
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
data class User(val id: Int, val name: String)
fun Application.module() {
install(ContentNegotiation) {
json()
}
routing {
get("/") {
call.respondText("Hello, World!", ContentType.Text.Plain)
}
get("/user/{id}") {
val id = call.parameters["id"]?.toIntOrNull()
if (id != null) {
val user = User(id, "User$id")
call.respond(user)
} else {
call.respond(HttpStatusCode.BadRequest, "Invalid ID")
}
}
post("/user") {
val user = call.receive<User>()
call.respond(HttpStatusCode.Created, user)
}
}
}
fun main() {
embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}本题详细解读
Ktor 框架简介
Ktor 是一个由 JetBrains 开发的 Kotlin 异步框架,用于构建轻量级的 Web 应用程序、HTTP 服务和微服务。它完全基于 Kotlin 协程,提供了简洁的 DSL(领域特定语言)来定义路由和处理请求。
代码解析
依赖导入:
io.ktor.application.*:包含 Ktor 应用程序的核心功能。io.ktor.features.ContentNegotiation:用于内容协商,支持 JSON 等格式的序列化和反序列化。io.ktor.http.*:包含 HTTP 相关的类和常量。io.ktor.request.*和io.ktor.response.*:用于处理请求和响应。io.ktor.routing.*:用于定义路由。io.ktor.serialization.json.*:用于 JSON 序列化和反序列化。io.ktor.server.engine.embeddedServer和io.ktor.server.netty.Netty:用于启动嵌入式服务器。
数据类:
User是一个简单的数据类,用于表示用户信息。
Application.module():
install(ContentNegotiation):安装内容协商功能,并配置 JSON 支持。routing:定义路由和处理程序。get("/"):处理根路径的 GET 请求,返回 "Hello, World!"。get("/user/{id}"):处理带有路径参数的 GET 请求,返回对应的用户信息。post("/user"):处理 POST 请求,接收 JSON 格式的用户信息并返回创建的用户。
main() 函数:
- 使用
embeddedServer启动一个 Netty 服务器,监听 8080 端口,并加载Application.module作为应用程序模块。
- 使用
运行与测试
- 运行该程序后,可以通过以下方式测试:
- 访问
http://localhost:8080/会返回 "Hello, World!"。 - 访问
http://localhost:8080/user/1会返回{"id":1,"name":"User1"}。 - 使用 POST 请求发送 JSON 数据到
http://localhost:8080/user,如{"id":2,"name":"User2"},会返回创建的用户信息。
- 访问