Communitygithub.com

kotlin-ktor-patterns

Ktor 服务端模式,包括路由 DSL、插件、认证、Koin 依赖注入、kotlinx.serialization、WebSocket 和 testApplication 测试。适用于构建 Ktor 服务器——路由、插件、认证、依赖注入、序列化或测试。

kotlin-ktor-patterns 是什么?

这个技能提供了构建健壮、可维护的 Ktor HTTP 服务器的全面模式和实践指南,充分利用 Kotlin 协程的优势。它涵盖了从项目结构、路由 DSL、内容协商与序列化(kotlinx.serialization)、JWT 认证、错误处理(StatusPages)、CORS 配置、Koin 依赖注入、请求验证到 WebSocket 支持的全栈开发流程。该技能适用于在终端(如 Cursor、Codex)中辅助开发者快速搭建 Ktor 项目,并确保代码遵循最佳实践。文档中提供了大量的代码示例和完整的项目布局,帮助开发者理解如何组织路由、配置插件、实现认证逻辑、管理依赖以及编写高效的集成测试。通过激活此技能,开发者可以避免重复造轮子,快速构建符合生产环境要求的 Ktor 应用。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Ktor 服务端模式

全面的 Ktor 模式,用于使用 Kotlin 协程构建健壮且可维护的 HTTP 服务器。

何时激活

  • 构建 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, "缺少 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, "缺少 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, "缺少 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>("令牌无效或已过期"))
            }
        }
    }
}

// 从 JWT 中提取用户 ID
fun ApplicationCall.userId(): String =
    principal<JWTPrincipal>()
        ?.payload
        ?.getClaim("userId")
        ?.asString()
        ?: throw AuthenticationException("令牌中没有 userId")

认证路由

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>("无效的凭据"),
                )
            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))
            }
        }
    }
}

StatusPages(错误处理)

// plugins/StatusPages.kt
fun Application.configureStatusPages() {
    install(StatusPages) {
        exception<ContentTransformationException> { call, cause ->
            call.respond(
                HttpStatusCode.BadRequest,
                ApiResponse.error<Unit>("无效的请求体: ${cause.message}"),
            )
        }

        exception<IllegalArgumentException> { call, cause ->
            call.respond(
                HttpStatusCode.BadRequest,
                ApiResponse.error<Unit>(cause.message ?: "错误的请求"),
            )
        }

        exception<AuthenticationException> { call, _ ->
            call.respond(
                HttpStatusCode.Unauthorized,
                ApiResponse.error<Unit>("需要认证"),
            )
        }

        exception<AuthorizationException> { call, _ ->
            call.respond(
                HttpStatusCode.Forbidden,
                ApiResponse.error<Unit>("访问被拒绝"),
            )
        }

        exception<NotFoundException> { call, cause ->
            call.respond(
                HttpStatusCode.NotFound,
                ApiResponse.error<Unit>(cause.message ?: "资源未找到"),
            )
        }

        exception<Throwable> { call, cause ->
            call.application.log.error("未处理的异常", cause)
            call.respond(
                HttpStatusCode.InternalServerError,
                ApiResponse.error<Unit>("服务器内部错误"),
            )
        }

        status(HttpStatusCode.NotFound) { call, status ->
            call.respond(status, ApiResponse.error<Unit>("路由未找到"))
        }
    }
}

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

// Application 设置
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 返回用户") {
            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>()

        // 验证
        require(request.name.isNotBlank()) { "名称是必需的" }
        require(request.name.length <= 100) { "名称长度不能超过 100 个字符" }
        require(request.email.matches(Regex(".+@.+\\..+"))) { "邮箱格式无效" }

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

// 或者使用验证扩展函数
fun CreateUserRequest.validate() {
    require(name.isNotBlank()) { "名称是必需的" }
    require(name.length <= 100) { "名称长度不能超过 100 个字符" }
    require(email.matches(Regex(".+@.+\\..+"))) { "邮箱格式无效" }
}

WebSocket

fun Application.configureWebSockets() {
    install(WebSockets) {
        pingPeriod = 15.seconds
        timeout = 15.seconds
        maxFrameSize = 64 * 1024 // 64 KiB — 仅在协议需要更大帧时增加
        masking = false // 根据 RFC 6455,服务端到客户端的帧未掩码;客户端到服务端的帧始终由 Ktor 掩码
    }
}

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

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

        try {
            send("已连接!在线用户数: ${connections.size}")

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

                // 在锁下快照以避免 ConcurrentModificationException
                val snapshot = synchronized(connections) { connections.toList() }
                snapshot.forEach { conn ->
                    conn.session.send(Json.encodeToString(message))
                }
            }
        } catch (e: Exception) {
            logger.error("WebSocket 错误", e)
        } finally {
            connections -= thisConnection
        }
    }
}

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



…

[翻译时截断了]

测试

使用 testApplication 进行集成测试

class UserRoutesTest {
    private val testModule = module {
        single<UserRepository> { mockk() }
        single { UserService(get()) }
    }

    @Test
    fun `get users returns 200`() = testApplication {
        application {
            configureSerialization()
            configureDI()
            configureRouting()
        }

        coEvery { userService.getAll() } returns listOf(testUser)

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

使用 TestClient 进行测试

class HealthRoutesTest {
    @Test
    fun `health endpoint returns ok`() = testApplication {
        application {
            configureRouting()
        }

        val response = client.get("/health")
        assertEquals(HttpStatusCode.OK, response.status)
        assertEquals("""{"status":"UP"}""", response.bodyAsText())
    }
}

配置

HOCON 配置

// application.conf
ktor {
    deployment {
        port = 8080
    }
    application {
        modules = [ com.example.ApplicationKt.module ]
    }
}

jwt {
    secret = "my-secret-key"
    issuer = "my-app"
    audience = "my-audience"
    realm = "my-realm"
}

环境变量覆盖

// 在 configureAuthentication 中使用
val jwtSecret = environment.config.propertyOrNull("jwt.secret")?.getString()
    ?: System.getenv("JWT_SECRET") ?: error("JWT_SECRET 未设置")

最佳实践

  1. 分层架构:将路由(routes)、服务(services)、仓库(repositories)和模型(models)分离,以保持关注点分离。
  2. 使用 kotlinx.serialization:使用 @Serializable 注解数据类,并利用 ignoreUnknownKeys 实现弹性。
  3. 集中式错误处理:使用 StatusPages 优雅地处理异常,而不是在每个路由中使用 try-catch 块。
  4. Koin for DI:在构造函数中注入依赖项,使代码易于测试。使用 by inject() 进行惰性注入。
  5. 认证:将路由组织为公共和受保护区域。使用 JWT 进行无状态认证。
  6. 请求验证:在服务层验证,使用 Kotlin 的 require() 或验证扩展函数。
  7. 测试:使用 testApplication 测试完整的 HTTP 请求/响应周期。对所有外部依赖使用 mock。
  8. CORS:在生产环境应用中明确声明允许的主机。在生产环境中避免使用 allowHost("*")。
  9. WebSocket:管理连接生命周期(连接、广播、断开连接)。使用同步的集合来避免并发修改。
  10. 配置:使用 HOCON 进行默认设置,使用环境变量进行秘密管理和环境特定覆盖。

另请参阅:完整的 Ktor 文档请访问 ktor.io。

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.

相关技能