Communitygithub.com

kotlin-ktor-patterns

Modèles de serveur Ktor incluant le DSL de routage, les plugins, l'authentification, l'injection de dépendances avec Koin, la sérialisation kotlinx.serialization, les WebSockets et les tests avec testApplication. À utiliser lors de la construction d'un serveur Ktor — routage, plugins, authentification, DI, sérialisation ou tests.

Qu'est-ce que kotlin-ktor-patterns ?

Ce skill fournit un ensemble complet de modèles et de bonnes pratiques pour construire des serveurs HTTP Ktor robustes et maintenables en utilisant les coroutines Kotlin. Il couvre l'ensemble du cycle de développement : de la configuration de l'application avec le DSL de routage, la négociation de contenu avec kotlinx.serialization, l'authentification JWT, la gestion d'erreurs via StatusPages, la configuration CORS, l'injection de dépendances avec Koin, jusqu'aux WebSockets et aux tests d'intégration avec testApplication. Il est conçu pour les développeurs utilisant Ktor (avec IntelliJ IDEA, VS Code, ou d'autres IDE) et détaille l'architecture des dossiers, les routes publiques et protégées, les validateurs de requêtes, ainsi que les tests unitaires et d'intégration. Les exemples de code incluent des configurations prêtes à l'emploi pour JWT, Koin, et les sérialiseurs personnalisés.

Compatible avec~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/kotlin-ktor-patterns

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Modèles de Serveur Ktor

Modèles Ktor complets pour construire des serveurs HTTP robustes et maintenables avec les coroutines Kotlin.

Quand Activer

  • Construction de serveurs HTTP Ktor
  • Configuration des plugins Ktor (Auth, CORS, ContentNegotiation, StatusPages)
  • Implémentation d'API REST avec Ktor
  • Mise en place de l'injection de dépendances avec Koin
  • Écriture de tests d'intégration Ktor avec testApplication
  • Travailler avec les WebSockets dans Ktor

Structure de l'Application

Disposition Standard d'un Projet Ktor

src/main/kotlin/
├── com/example/
│   ├── Application.kt           # Point d'entrée, configuration des modules
│   ├── plugins/
│   │   ├── Routing.kt           # Définitions des routes
│   │   ├── Serialization.kt     # Configuration de la négociation de contenu
│   │   ├── Authentication.kt    # Configuration de l'authentification
│   │   ├── StatusPages.kt       # Gestion des erreurs
│   │   └── CORS.kt              # Configuration CORS
│   ├── routes/
│   │   ├── UserRoutes.kt        # Points d'accès /users
│   │   ├── AuthRoutes.kt        # Points d'accès /auth
│   │   └── HealthRoutes.kt      # Points d'accès /health
│   ├── models/
│   │   ├── User.kt              # Modèles de domaine
│   │   └── ApiResponse.kt       # Enveloppes de réponse
│   ├── services/
│   │   ├── UserService.kt       # Logique métier
│   │   └── AuthService.kt       # Logique d'authentification
│   ├── repositories/
│   │   ├── UserRepository.kt    # Interface d'accès aux données
│   │   └── ExposedUserRepository.kt
│   └── di/
│       └── AppModule.kt         # Modules Koin
src/test/kotlin/
├── com/example/
│   ├── routes/
│   │   └── UserRoutesTest.kt
│   └── services/
│       └── UserServiceTest.kt

Point d'Entrée de l'Application

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

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

DSL de Routage

Routes de Base

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

Organisation des Routes avec Authentification

fun Route.userRoutes() {
    route("/users") {
        // Routes publiques
        get { /* lister les utilisateurs */ }
        get("/{id}") { /* obtenir un utilisateur */ }

        // Routes protégées
        authenticate("jwt") {
            post { /* créer un utilisateur - nécessite authentification */ }
            put("/{id}") { /* mettre à jour un utilisateur - nécessite authentification */ }
            delete("/{id}") { /* supprimer un utilisateur - nécessite authentification */ }
        }
    }
}

Négociation de Contenu & Sérialisation

Configuration de kotlinx.serialization

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

Modèles Sérialisables

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

Sérialiseurs Personnalisés

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

Authentification

Authentification 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>("Jeton invalide ou expiré"))
            }
        }
    }
}

// Extraction de l'utilisateur à partir du JWT
fun ApplicationCall.userId(): String =
    principal<JWTPrincipal>()
        ?.payload
        ?.getClaim("userId")
        ?.asString()
        ?: throw AuthenticationException("Aucun userId dans le jeton")

Routes d'Authentification

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>("Identifiants invalides"),
                )
            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))
            }
        }
    }
}

Pages d'État (Gestion des Erreurs)

// plugins/StatusPages.kt
fun Application.configureStatusPages() {
    install(StatusPages) {
        exception<ContentTransformationException> { call, cause ->
            call.respond(
                HttpStatusCode.BadRequest,
                ApiResponse.error<Unit>("Corps de requête invalide : ${cause.message}"),
            )
        }

        exception<IllegalArgumentException> { call, cause ->
            call.respond(
                HttpStatusCode.BadRequest,
                ApiResponse.error<Unit>(cause.message ?: "Requête incorrecte"),
            )
        }

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

        exception<AuthorizationException> { call, _ ->
            call.respond(
                HttpStatusCode.Forbidden,
                ApiResponse.error<Unit>("Accès refusé"),
            )
        }

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

        exception<Throwable> { call, cause ->
            call.application.log.error("Exception non gérée", cause)
            call.respond(
                HttpStatusCode.InternalServerError,
                ApiResponse.error<Unit>("Erreur interne du serveur"),
            )
        }

        status(HttpStatusCode.NotFound) { call, status ->
            call.respond(status, ApiResponse.error<Unit>("Route non trouvée"))
        }
    }
}

Configuration 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
    }
}

Injection de Dépendances avec Koin

Définition du Module

// di/AppModule.kt
val appModule = module {
    // Base de données
    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()) }
}

// Configuration de l'application
fun Application.configureDI() {
    install(Koin) {
        modules(appModule)
    }
}

Utilisation de Koin dans les Routes

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

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

Koin pour les 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 retourne l'utilisateur") {
            coEvery { repository.findById("1") } returns testUser
            service.getById("1") shouldBe testUser
        }
    }
}

Validation des Requêtes

// Valider les données de requête dans les routes
fun Route.userRoutes() {
    val userService by inject<UserService>()

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

        // Validation
        require(request.name.isNotBlank()) { "Le nom est requis" }
        require(request.name.length <= 100) { "Le nom doit faire 100 caractères ou moins" }
        require(request.email.matches(Regex(".+@.+\\.+"))) { "Format d'email invalide" }

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

// Ou utiliser une extension de validation
fun CreateUserRequest.validate() {
    require(name.isNotBlank()) { "Le nom est requis" }
    require(name.length <= 100) { "Le nom doit faire 100 caractères ou moins" }
    require(email.matches(Regex(".+@.+\\.+"))) { "Format d'email invalide" }
}

WebSockets

fun Application.configureWebSockets() {
    install(WebSockets) {
        pingPeriod = 15.seconds
        timeout = 15.seconds
        maxFrameSize = 64 * 1024 // 64 KiB — augmenter seulement si votre protocole nécessite des trames plus grandes
        masking = false // Les trames serveur vers client ne sont pas masquées selon la RFC 6455 ; les trames client vers serveur sont toujours masquées par Ktor
    }
}

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

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

        try {
            send("Connecté ! Utilisateurs en ligne : ${connections.size}")

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

                // Instantané sous verrou pour éviter ConcurrentModificationException
                val snapshot = synchronized(connections) { connections.toList() }
                snapshot.forEach { conn ->
                    conn.session.send(Json.encodeToString(message))
                }
            }
        } catch (e: Exception) {
            logger.error("Erreur WebSocket", e)
        } finally {
            connections -= thisConnection
        }
    }
}

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

Tests d'Intégration

Configuration de testApplication

// build.gradle.kts
val ktorVersion = "2.3.7"
dependencies {
    testImplementation("io.ktor:ktor-server-test-host:${ktorVersion}")
    testImplementation("io.ktor:ktor-client-content-negotiation:${ktorVersion}")
}

Test de Routes

class UserRoutesTest : FunSpec({
    val app = testApplication {
        environment {
            config = MapApplicationConfig(
                "jwt.secret" to "test-secret",
                "jwt.issuer" to "test-issuer",
                "jwt.audience" to "test-audience",
                "jwt.realm" to "test-realm",
            )
        }
        application {
            configureSerialization()
            configureStatusPages()
            configureRouting()
        }
    }

    test("GET /users retourne la liste des utilisateurs") {
        app.client.get("/users").apply {
            status shouldBe HttpStatusCode.OK
        }
    }

    test("POST /users crée un utilisateur") {
        app.client.post("/users") {
            contentType(ContentType.Application.Json)
            setBody(CreateUserRequest(name = "Test", email = "[email protected]"))
        }.apply {
            status shouldBe HttpStatusCode.Created
        }
    }

    test("GET /users/1 retourne un utilisateur") {
        app.client.get("/users/1").apply {
            status shouldBe HttpStatusCode.OK
        }
    }

    test("GET /users/999 retourne 404") {
        app.client.get("/users/999").apply {
            status shouldBe HttpStatusCode.NotFound
        }
    }

    test("POST /users avec des données invalides retourne 400") {
        app.client.post("/users") {
            contentType(ContentType.Application.Json)
            setBody(CreateUserRequest(name = "", email = ""))
        }.apply {
            status shouldBe HttpStatusCode.BadRequest
        }
    }

    test("DELETE /users/999 retourne 404") {
        app.client.delete("/users/999").apply {
            status shouldBe HttpStatusCode.NotFound
        }
    }
})

Test de WebSockets

class WebSocketTest : FunSpec({
    val app = testApplication {
        application {
            configureWebSockets()
            configureRouting()
        }
    }

    test("Connexion et messages WebSocket") {
        val client = app.client
        val session = client.webSocketSession("/chat")

        var message = session.incoming.receive() as Frame.Text
        message.readText() should startWith("Connecté !")

        session.send(Frame.Text("Bonjour"))

        message = session.incoming.receive() as Frame.Text
        val parsed = Json.decodeFromString<ChatMessage>(message.readText())
        parsed.text shouldBe "Bonjour"
    }
})

Documents Associés

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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Skills associés