🚀 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)
}
}
}