Communitygithub.com

Ktor-Server-Patterns

Ktor-Server-Muster inklusive Routing-DSL, Plugins, Authentifizierung, Koin-DI, kotlinx.serialization, WebSockets und testApplication-Testing. Verwenden Sie dies beim Erstellen eines Ktor-Servers – Routing, Plugins, Auth, DI, Serialisierung oder Tests.

Was ist Ktor-Server-Patterns?

Diese Skill-Anleitung bietet umfassende Muster und Best Practices für den Aufbau robuster und wartbarer HTTP-Server mit Ktor und Kotlin-Koroutinen. Sie deckt eine breite Palette von Themen ab, darunter die Routing-DSL mit öffentlichen und geschützten Endpunkten, die Konfiguration von Plugins wie Content Negotiation (kotlinx.serialization), JWT-Authentifizierung, CORS und StatusPages für zentralisierte Fehlerbehandlung. Darüber hinaus wird die Abhängigkeitsinjektion mit Koin demonstriert, sowohl für die Anwendungslogik als auch für Tests. Die Anleitung unterstützt die gängigsten Ktor-Plattformen und Entwicklungsworkflows, von der Projektstruktur bis hin zu WebSockets und Integrationstests mit testApplication. Entwickler lernen, wie sie saubere, modularisierte Anwendungen erstellen, die den Prinzipien der Trennung von Belangen und testbaren Komponenten folgen.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/kotlin-ktor-patterns

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Ktor-Server-Muster

Umfassende Ktor-Muster für den Bau robuster, wartbarer HTTP-Server mit Kotlin-Koroutinen.

Wann aktivieren

  • Erstellen von Ktor-HTTP-Servern
  • Konfigurieren von Ktor-Plugins (Auth, CORS, ContentNegotiation, StatusPages)
  • Implementieren von REST-APIs mit Ktor
  • Einrichten der Abhängigkeitsinjektion mit Koin
  • Schreiben von Ktor-Integrationstests mit testApplication
  • Arbeiten mit WebSockets in Ktor

Anwendungsstruktur

Standard Ktor-Projektlayout

src/main/kotlin/
├── com/example/
│   ├── Application.kt           # Einstiegspunkt, Modulkonfiguration
│   ├── plugins/
│   │   ├── Routing.kt           # Routendefinitionen
│   │   ├── Serialization.kt     # Content-Negotiation-Einrichtung
│   │   ├── Authentication.kt    # Auth-Konfiguration
│   │   ├── StatusPages.kt       # Fehlerbehandlung
│   │   └── CORS.kt              # CORS-Konfiguration
│   ├── routes/
│   │   ├── UserRoutes.kt        # /users-Endpunkte
│   │   ├── AuthRoutes.kt        # /auth-Endpunkte
│   │   └── HealthRoutes.kt      # /health-Endpunkte
│   ├── models/
│   │   ├── User.kt              # Domain-Modelle
│   │   └── ApiResponse.kt       # Antwortenhüllen
│   ├── services/
│   │   ├── UserService.kt       # Geschäftslogik
│   │   └── AuthService.kt       # Auth-Logik
│   ├── repositories/
│   │   ├── UserRepository.kt    # Datenzugriffsschnittstelle
│   │   └── ExposedUserRepository.kt
│   └── di/
│       └── AppModule.kt         # Koin-Module
src/test/kotlin/
├── com/example/
│   ├── routes/
│   │   └── UserRoutesTest.kt
│   └── services/
│       └── UserServiceTest.kt

Anwendungseinstiegspunkt

// Application.kt
fun main() {
    embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}

fun Application.module() {
    configureSerialization()
    configureAuthentication()
    configureStatusPages()
    configureCORS()
    configureDI()
    configureRouting()
}

Routing-DSL

Grundlegende Routen

// 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, "Fehlende 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, "Fehlende 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, "Fehlende ID")
            val deleted = userService.delete(id)
            if (deleted) call.respond(HttpStatusCode.NoContent)
            else call.respond(HttpStatusCode.NotFound)
        }
    }
}

Routenorganisation mit authentifizierten Routen

fun Route.userRoutes() {
    route("/users") {
        // Öffentliche Routen
        get { /* Benutzer auflisten */ }
        get("/{id}") { /* Benutzer abrufen */ }

        // Geschützte Routen
        authenticate("jwt") {
            post { /* Benutzer erstellen – erfordert Auth */ }
            put("/{id}") { /* Benutzer aktualisieren – erfordert Auth */ }
            delete("/{id}") { /* Benutzer löschen – erfordert Auth */ }
        }
    }
}

Content Negotiation und Serialisierung

kotlinx.serialization Einrichtung

// plugins/Serialization.kt
fun Application.configureSerialization() {
    install(ContentNegotiation) {
        json(Json {
            prettyPrint = true
            isLenient = false
            ignoreUnknownKeys = true
            encodeDefaults = true
            explicitNulls = false
        })
    }
}

Serialisierbare Modelle

@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,
)

Benutzerdefinierte Serialisierer

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

Authentifizierung

JWT-Authentifizierung

// 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>("Ungültiges oder abgelaufenes Token"))
            }
        }
    }
}

// Benutzer aus JWT extrahieren
fun ApplicationCall.userId(): String =
    principal<JWTPrincipal>()
        ?.payload
        ?.getClaim("userId")
        ?.asString()
        ?: throw AuthenticationException("Keine userId im Token")

Auth-Routen

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>("Ungültige Anmeldedaten"),
                )
            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))
            }
        }
    }
}

Status Pages (Fehlerbehandlung)

// plugins/StatusPages.kt
fun Application.configureStatusPages() {
    install(StatusPages) {
        exception<ContentTransformationException> { call, cause ->
            call.respond(
                HttpStatusCode.BadRequest,
                ApiResponse.error<Unit>("Ungültiger Anforderungstext: ${cause.message}"),
            )
        }

        exception<IllegalArgumentException> { call, cause ->
            call.respond(
                HttpStatusCode.BadRequest,
                ApiResponse.error<Unit>(cause.message ?: "Ungültige Anfrage"),
            )
        }

        exception<AuthenticationException> { call, _ ->
            call.respond(
                HttpStatusCode.Unauthorized,
                ApiResponse.error<Unit>("Authentifizierung erforderlich"),
            )
        }

        exception<AuthorizationException> { call, _ ->
            call.respond(
                HttpStatusCode.Forbidden,
                ApiResponse.error<Unit>("Zugriff verweigert"),
            )
        }

        exception<NotFoundException> { call, cause ->
            call.respond(
                HttpStatusCode.NotFound,
                ApiResponse.error<Unit>(cause.message ?: "Ressource nicht gefunden"),
            )
        }

        exception<Throwable> { call, cause ->
            call.application.log.error("Unbehandelte Ausnahme", cause)
            call.respond(
                HttpStatusCode.InternalServerError,
                ApiResponse.error<Unit>("Interner Serverfehler"),
            )
        }

        status(HttpStatusCode.NotFound) { call, status ->
            call.respond(status, ApiResponse.error<Unit>("Route nicht gefunden"))
        }
    }
}

CORS-Konfiguration

// 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-Abhängigkeitsinjektion

Moduldefinition

// di/AppModule.kt
val appModule = module {
    // Datenbank
    single<Database> { DatabaseFactory.create(get()) }

    // Repositories
    single<UserRepository> { ExposedUserRepository(get()) }
    single<OrderRepository> { ExposedOrderRepository(get()) }

    // Services
    single { UserService(get()) }
    single { OrderService(get(), get()) }
    single { AuthService(get(), get()) }
}

// Anwendungseinrichtung
fun Application.configureDI() {
    install(Koin) {
        modules(appModule)
    }
}

Koin in Routen verwenden

fun Route.userRoutes() {
    val userService by inject<UserService>()

    route("/users") {
        get {
            val users = userService.getAll()
            call.respond(ApiResponse.ok(users))
        }
    }
}

Koin für Tests

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 gibt Benutzer zurück") {
            coEvery { repository.findById("1") } returns testUser
            service.getById("1") shouldBe testUser
        }
    }
}

Anforderungsvalidierung

// Validierung von Anfragedaten in Routen
fun Route.userRoutes() {
    val userService by inject<UserService>()

    post("/users") {
        val request = call.receive<CreateUserRequest>()

        // Validieren
        require(request.name.isNotBlank()) { "Name ist erforderlich" }
        require(request.name.length <= 100) { "Name darf maximal 100 Zeichen lang sein" }
        require(request.email.matches(Regex(".+@.+\\.+"))) { "Ungültiges E-Mail-Format" }

        val user = userService.create(request)
        call.respond(HttpStatusCode.Created, ApiResponse.ok(user))
    }
}

// Oder eine Validierungserweiterung verwenden
fun CreateUserRequest.validate() {
    require(name.isNotBlank()) { "Name ist erforderlich" }
    require(name.length <= 100) { "Name darf maximal 100 Zeichen lang sein" }
    require(email.matches(Regex(".+@.+\\.+"))) { "Ungültiges E-Mail-Format" }
}

WebSockets

fun Application.configureWebSockets() {
    install(WebSockets) {
        pingPeriod = 15.seconds
        timeout = 15.seconds
        maxFrameSize = 64 * 1024 // 64 KiB – nur erhöhen, wenn Ihr Protokoll größere Frames erfordert
        masking = false // Server-zu-Client-Frames sind gemäß RFC 6455 ungemaskiert; Client-zu-Server werden von Ktor immer maskiert
    }
}

fun Route.chatRoutes() {
    val connections = Collections.synchronizedSet<Connection>(LinkedHashSet())

    webSocket("/chat") {
        val thisConnection = Connection(this)
        connections += thisConnection

        try {
            send("Verbunden! Benutzer online: ${connections.size}")

            for (frame in incoming) {
                frame as? Frame.Text ?: continue
                val text = frame.readText()
                val message = ChatMessage(thisConnection.name, text)

                // Snapshot unter Sperre, um ConcurrentModificationException zu vermeiden
                val snapshot = synchronized(connections) { connections.toList() }
                snapshot.forEach { conn ->
                    conn.session.send(Json.encodeToString(message))
                }
            }
        } catch (e: Exception) {
            logger.error("WebSocket-Fehler", e)
        } finally {
            connections -= thisConnection
        }
    }
}

data class Connection(val session: DefaultWebSocketSession) {
    val name: String = "User-${counter.getAndIncrement()}"

testApplication Tests

Integrationstests einrichten

// test/kotlin/routes/UserRoutesTest.kt
class UserRoutesTest {

    @Test
    fun `should get all users`() = testApplication {
        application {
            module()
        }

        val response = client.get("/users")
        assertEquals(HttpStatusCode.OK, response.status)
    }

    @Test
    fun `should create a new user`() = testApplication {
        application {
            module()
        }

        val newUser = CreateUserRequest(
            name = "John Doe",
            email = "[email protected]"
        )
        val response = client.post("/users") {
            contentType(ContentType.Application.Json)
            setBody(newUser)
        }
        assertEquals(HttpStatusCode.Created, response.status)
    }

    @Test
    fun `should return 404 for unknown user`() = testApplication {
        application {
            module()
        }

        val response = client.get("/users/999")
        assertEquals(HttpStatusCode.NotFound, response.status)
    }
}

Docker-Containerisierung

# Dockerfile
FROM openjdk:17-jdk-alpine
WORKDIR /app
COPY build/libs/ktor-server.jar /app/ktor-server.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "ktor-server.jar"]

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

Verwandte Skills