Ktor 서버 패턴
Kotlin 코루틴을 사용하여 견고하고 유지보수 가능한 HTTP 서버를 구축하기 위한 포괄적인 Ktor 패턴입니다.
활성화 시점
- Ktor HTTP 서버 구축
- Ktor 플러그인 구성 (Auth, CORS, ContentNegotiation, StatusPages)
- Ktor로 REST API 구현
- Koin으로 의존성 주입 설정
- testApplication으로 Ktor 통합 테스트 작성
- Ktor에서 WebSocket 작업
애플리케이션 구조
표준 Ktor 프로젝트 레이아웃
src/main/kotlin/
├── com/example/
│ ├── Application.kt # 진입점, 모듈 구성
│ ├── plugins/
│ │ ├── Routing.kt # 라우트 정의
│ │ ├── Serialization.kt # 콘텐츠 협상 설정
│ │ ├── Authentication.kt # 인증 구성
│ │ ├── StatusPages.kt # 오류 처리
│ │ └── CORS.kt # CORS 구성
│ ├── routes/
│ │ ├── UserRoutes.kt # /users 엔드포인트
│ │ ├── AuthRoutes.kt # /auth 엔드포인트
│ │ └── HealthRoutes.kt # /health 엔드포인트
│ ├── models/
│ │ ├── User.kt # 도메인 모델
│ │ └── ApiResponse.kt # 응답 래퍼
│ ├── services/
│ │ ├── UserService.kt # 비즈니스 로직
│ │ └── AuthService.kt # 인증 로직
│ ├── repositories/
│ │ ├── UserRepository.kt # 데이터 액세스 인터페이스
│ │ └── ExposedUserRepository.kt
│ └── di/
│ └── AppModule.kt # Koin 모듈
src/test/kotlin/
├── com/example/
│ ├── routes/
│ │ └── UserRoutesTest.kt
│ └── services/
│ └── UserServiceTest.kt
애플리케이션 진입점
// Application.kt
fun main() {
embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}
fun Application.module() {
configureSerialization()
configureAuthentication()
configureStatusPages()
configureCORS()
configureDI()
configureRouting()
}
라우팅 DSL
기본 라우트
// plugins/Routing.kt
fun Application.configureRouting() {
routing {
userRoutes()
authRoutes()
healthRoutes()
}
}
// routes/UserRoutes.kt
fun Route.userRoutes() {
val userService by inject<UserService>()
route("/users") {
get {
val users = userService.getAll()
call.respond(users)
}
get("/{id}") {
val id = call.parameters["id"]
?: return@get call.respond(HttpStatusCode.BadRequest, "Missing id")
val user = userService.getById(id)
?: return@get call.respond(HttpStatusCode.NotFound)
call.respond(user)
}
post {
val request = call.receive<CreateUserRequest>()
val user = userService.create(request)
call.respond(HttpStatusCode.Created, user)
}
put("/{id}") {
val id = call.parameters["id"]
?: return@put call.respond(HttpStatusCode.BadRequest, "Missing id")
val request = call.receive<UpdateUserRequest>()
val user = userService.update(id, request)
?: return@put call.respond(HttpStatusCode.NotFound)
call.respond(user)
}
delete("/{id}") {
val id = call.parameters["id"]
?: return@delete call.respond(HttpStatusCode.BadRequest, "Missing id")
val deleted = userService.delete(id)
if (deleted) call.respond(HttpStatusCode.NoContent)
else call.respond(HttpStatusCode.NotFound)
}
}
}
인증된 라우트를 사용한 라우트 구성
fun Route.userRoutes() {
route("/users") {
// 공개 라우트
get { /* 사용자 목록 */ }
get("/{id}") { /* 사용자 조회 */ }
// 보호된 라우트
authenticate("jwt") {
post { /* 사용자 생성 - 인증 필요 */ }
put("/{id}") { /* 사용자 업데이트 - 인증 필요 */ }
delete("/{id}") { /* 사용자 삭제 - 인증 필요 */ }
}
}
}
콘텐츠 협상 및 직렬화
kotlinx.serialization 설정
// plugins/Serialization.kt
fun Application.configureSerialization() {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = false
ignoreUnknownKeys = true
encodeDefaults = true
explicitNulls = false
})
}
}
직렬화 가능 모델
@Serializable
data class UserResponse(
val id: String,
val name: String,
val email: String,
val role: Role,
@Serializable(with = InstantSerializer::class)
val createdAt: Instant,
)
@Serializable
data class CreateUserRequest(
val name: String,
val email: String,
val role: Role = Role.USER,
)
@Serializable
data class ApiResponse<T>(
val success: Boolean,
val data: T? = null,
val error: String? = null,
) {
companion object {
fun <T> ok(data: T): ApiResponse<T> = ApiResponse(success = true, data = data)
fun <T> error(message: String): ApiResponse<T> = ApiResponse(success = false, error = message)
}
}
@Serializable
data class PaginatedResponse<T>(
val data: List<T>,
val total: Long,
val page: Int,
val limit: Int,
)
사용자 정의 직렬 변환기
object InstantSerializer : KSerializer<Instant> {
override val descriptor = PrimitiveSerialDescriptor("Instant", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Instant) =
encoder.encodeString(value.toString())
override fun deserialize(decoder: Decoder): Instant =
Instant.parse(decoder.decodeString())
}
인증
JWT 인증
// plugins/Authentication.kt
fun Application.configureAuthentication() {
val jwtSecret = environment.config.property("jwt.secret").getString()
val jwtIssuer = environment.config.property("jwt.issuer").getString()
val jwtAudience = environment.config.property("jwt.audience").getString()
val jwtRealm = environment.config.property("jwt.realm").getString()
install(Authentication) {
jwt("jwt") {
realm = jwtRealm
verifier(
JWT.require(Algorithm.HMAC256(jwtSecret))
.withAudience(jwtAudience)
.withIssuer(jwtIssuer)
.build()
)
validate { credential ->
if (credential.payload.audience.contains(jwtAudience)) {
JWTPrincipal(credential.payload)
} else {
null
}
}
challenge { _, _ ->
call.respond(HttpStatusCode.Unauthorized, ApiResponse.error<Unit>("Invalid or expired token"))
}
}
}
}
// JWT에서 사용자 추출
fun ApplicationCall.userId(): String =
principal<JWTPrincipal>()
?.payload
?.getClaim("userId")
?.asString()
?: throw AuthenticationException("No userId in token")
인증 라우트
fun Route.authRoutes() {
val authService by inject<AuthService>()
route("/auth") {
post("/login") {
val request = call.receive<LoginRequest>()
val token = authService.login(request.email, request.password)
?: return@post call.respond(
HttpStatusCode.Unauthorized,
ApiResponse.error<Unit>("Invalid credentials"),
)
call.respond(ApiResponse.ok(TokenResponse(token)))
}
post("/register") {
val request = call.receive<RegisterRequest>()
val user = authService.register(request)
call.respond(HttpStatusCode.Created, ApiResponse.ok(user))
}
authenticate("jwt") {
get("/me") {
val userId = call.userId()
val user = authService.getProfile(userId)
call.respond(ApiResponse.ok(user))
}
}
}
}
상태 페이지 (오류 처리)
// plugins/StatusPages.kt
fun Application.configureStatusPages() {
install(StatusPages) {
exception<ContentTransformationException> { call, cause ->
call.respond(
HttpStatusCode.BadRequest,
ApiResponse.error<Unit>("Invalid request body: ${cause.message}"),
)
}
exception<IllegalArgumentException> { call, cause ->
call.respond(
HttpStatusCode.BadRequest,
ApiResponse.error<Unit>(cause.message ?: "Bad request"),
)
}
exception<AuthenticationException> { call, _ ->
call.respond(
HttpStatusCode.Unauthorized,
ApiResponse.error<Unit>("Authentication required"),
)
}
exception<AuthorizationException> { call, _ ->
call.respond(
HttpStatusCode.Forbidden,
ApiResponse.error<Unit>("Access denied"),
)
}
exception<NotFoundException> { call, cause ->
call.respond(
HttpStatusCode.NotFound,
ApiResponse.error<Unit>(cause.message ?: "Resource not found"),
)
}
exception<Throwable> { call, cause ->
call.application.log.error("Unhandled exception", cause)
call.respond(
HttpStatusCode.InternalServerError,
ApiResponse.error<Unit>("Internal server error"),
)
}
status(HttpStatusCode.NotFound) { call, status ->
call.respond(status, ApiResponse.error<Unit>("Route not found"))
}
}
}
CORS 구성
// plugins/CORS.kt
fun Application.configureCORS() {
install(CORS) {
allowHost("localhost:3000")
allowHost("example.com", schemes = listOf("https"))
allowHeader(HttpHeaders.ContentType)
allowHeader(HttpHeaders.Authorization)
allowMethod(HttpMethod.Put)
allowMethod(HttpMethod.Delete)
allowMethod(HttpMethod.Patch)
allowCredentials = true
maxAgeInSeconds = 3600
}
}
Koin 의존성 주입
모듈 정의
// di/AppModule.kt
val appModule = module {
// 데이터베이스
single<Database> { DatabaseFactory.create(get()) }
// 리포지토리
single<UserRepository> { ExposedUserRepository(get()) }
single<OrderRepository> { ExposedOrderRepository(get()) }
// 서비스
single { UserService(get()) }
single { OrderService(get(), get()) }
single { AuthService(get(), get()) }
}
// 애플리케이션 설정
fun Application.configureDI() {
install(Koin) {
modules(appModule)
}
}
라우트에서 Koin 사용
fun Route.userRoutes() {
val userService by inject<UserService>()
route("/users") {
get {
val users = userService.getAll()
call.respond(ApiResponse.ok(users))
}
}
}
테스트를 위한 Koin
class UserServiceTest : FunSpec(), KoinTest {
override fun extensions() = listOf(KoinExtension(testModule))
private val testModule = module {
single<UserRepository> { mockk() }
single { UserService(get()) }
}
private val repository by inject<UserRepository>()
private val service by inject<UserService>()
init {
test("getUser returns user") {
coEvery { repository.findById("1") } returns testUser
service.getById("1") shouldBe testUser
}
}
}
요청 유효성 검사
// 라우트에서 요청 데이터 검증
fun Route.userRoutes() {
val userService by inject<UserService>()
post("/users") {
val request = call.receive<CreateUserRequest>()
// Validate
require(request.name.isNotBlank()) { "Name is required" }
require(request.name.length <= 100) { "Name must be 100 characters or less" }
require(request.email.matches(Regex(".+@.+\\..+"))) { "Invalid email format" }
val user = userService.create(request)
call.respond(HttpStatusCode.Created, ApiResponse.ok(user))
}
}
// 또는 유효성 검사 확장 함수 사용
fun CreateUserRequest.validate() {
require(name.isNotBlank()) { "Name is required" }
require(name.length <= 100) { "Name must be 100 characters or less" }
require(email.matches(Regex(".+@.+\\..+"))) { "Invalid email format" }
}
웹소켓
fun Application.configureWebSockets() {
install(WebSockets) {
pingPeriod = 15.seconds
timeout = 15.seconds
maxFrameSize = 64 * 1024 // 64 KiB — Increase only if your protocol requires larger frames
masking = false // Server-to-client frames are unmasked per RFC 6455; client-to-server are always masked by Ktor
}
}
fun Route.chatRoutes() {
val connections = Collections.synchronizedSet<Connection>(LinkedHashSet())
webSocket("/chat") {
val thisConnection = Connection(this)
connections += thisConnection
try {
send("Connected! Users online: ${connections.size}")
for (frame in incoming) {
frame as? Frame.Text ?: continue
val text = frame.readText()
val message = ChatMessage(thisConnection.name, text)
// Snapshot under lock to avoid ConcurrentModificationException
val snapshot = synchronized(connections) { connections.toList() }
snapshot.forEach { conn ->
conn.session.send(Json.encodeToString(message))
}
}
} catch (e: Exception) {
logger.error("WebSocket error", e)
} finally {
connections -= thisConnection
}
}
}
data class Connection(val session: DefaultWebSocketSession) {
val name: String = "User-${counter.getAndIncrement()}"
companion object {
private val counter = AtomicInteger(1)
}
}
@Serializable
data class ChatMessage(
val user: String,
val text: String,
val timestamp: Long = Clock.System.now().toEpochMilliseconds(),
)
테스트
testApplication을 사용한 통합 테스트
// build.gradle.kts
/*
dependencies {
testImplementation("io.ktor:ktor-server-test-host-jvm")
testImplementation("io.ktor:ktor-client-content-negotiation-jvm")
testImplementation("io.kotest:kotest-runner-junit5:5.9.1")
testImplementation("io.mockk:mockk:1.13.12")
}
*/
class UserRoutesTest : FunSpec({
val userRepository = mockk<UserRepository>()
val testModule = module {
single<UserRepository> { userRepository }
single { UserService(get()) }
}
testApplication {
application {
configureSerialization()
configureStatusPages()
configureDI(listOf(testModule))
configureRouting()
}
val client = createClient {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
})
}
}
test("GET /users returns list of users") {
coEvery { userRepository.findAll() } returns listOf(testUser)
val response = client.get("/users")
response.status shouldBe HttpStatusCode.OK
response.body<UserRoutesTest>() shouldBe listOf(testUser)
}
test("GET /users/{id} returns 404 for non-existent user") {
coEvery { userRepository.findById("999") } returns null
val response = client.get("/users/999")
response.status shouldBe HttpStatusCode.NotFound
}
}
})
서비스 단위 테스트
class UserServiceTest : FunSpec({
val userRepository = mockk<UserRepository>()
val userService = UserService(userRepository)
test("createUser should save user and return result") {
val request = CreateUserRequest("John", "[email protected]")
val savedUser = User(id = "1", name = "John", email = "[email protected]")
coEvery { userRepository.save(any()) } returns savedUser
val result = userService.create(request)
result shouldBe savedUser
coVerify { userRepository.save(any()) }
}
})