🚀 Introduction à Ktor
📖 Qu'est-ce que Ktor ?
Ktor est un framework web asynchrone léger construit avec Kotlin. Il vous permet de créer facilement des serveurs rapides et efficaces basés sur les coroutines !
💡 Création d'un Projet
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")
}
🎯 Premier Serveur
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)
}
Après l'exécution, visitez http://localhost:8080 dans votre navigateur !
Plusieurs Routes
fun main() {
embeddedServer(Netty, port = 8080) {
routing {
get("/") {
call.respondText("홈페이지")
}
get("/hello") {
call.respondText("안녕하세요!")
}
get("/about") {
call.respondText("소개 페이지")
}
}
}.start(wait = true)
}
🎨 Routage
Paramètres de Chemin
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
Paramètres de Requête
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
🔧 Réponses JSON
Configuration de 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")
}
Réponses 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)
}
}
}
🎯 Exemple Pratique
API Simple
@Serializable
data class Product(
val id: Int,
val name: String,
val price: Double
)
fun Application.productAPI() {
install(ContentNegotiation) {
json()
}
val products = mutableListOf(
Product(1, "노트북", 1500000.0),
Product(2, "마우스", 30000.0),
Product(3, "키보드", 80000.0)
)
routing {
// 전체 상품 조회
get("/products") {
call.respond(products)
}
// 특정 상품 조회
get("/products/{id}") {
val id = call.parameters["id"]?.toInt()
val product = products.find { it.id == id }
if (product != null) {
call.respond(product)
} else {
call.respondText("상품을 찾을 수 없습니다", status = HttpStatusCode.NotFound)
}
}
}
}
fun main() {
embeddedServer(Netty, port = 8080) {
productAPI()
}.start(wait = true)
}
Codes d'État
import io.ktor.http.*
routing {
get("/status/ok") {
call.respondText("정상", status = HttpStatusCode.OK)
}
get("/status/created") {
call.respondText("생성됨", status = HttpStatusCode.Created)
}
get("/status/not-found") {
call.respondText("없음", status = HttpStatusCode.NotFound)
}
get("/status/error") {
call.respondText("서버 오류", status = HttpStatusCode.InternalServerError)
}
}
🔥 Middleware
Journalisation
import io.ktor.server.plugins.callloging.*
fun Application.module() {
install(CallLogging)
routing {
get("/") {
call.respondText("Hello!")
}
}
}
// 콘솔에 요청 로그 출력
Configuration CORS
import io.ktor.server.plugins.cors.routing.*
fun Application.module() {
install(CORS) {
anyHost() // 모든 호스트 허용 (개발 환경)
allowHeader(HttpHeaders.ContentType)
}
routing {
get("/api/data") {
call.respond(mapOf("message" to "CORS 설정됨"))
}
}
}
🛠️ Structure de l'Application
Modularisation
// routes/UserRoutes.kt
fun Route.userRoutes() {
route("/users") {
get {
call.respond(listOf("User1", "User2"))
}
get("/{id}") {
val id = call.parameters["id"]
call.respondText("User $id")
}
}
}
// routes/ProductRoutes.kt
fun Route.productRoutes() {
route("/products") {
get {
call.respond(listOf("Product1", "Product2"))
}
}
}
// Application.kt
fun Application.module() {
install(ContentNegotiation) {
json()
}
routing {
userRoutes()
productRoutes()
}
}