Skip to content

Everything Claude Code 的 kotlin-ktor-patterns Skill 提供了一套生产级的 Ktor 服务端开发模式,覆盖路由组织、插件集成、Koin 依赖注入、序列化、WebSockets 以及 testApplication 测试等核心环节。通过标准化项目结构与最佳实践,这一 Skill 能让 AI 编程助手(如 Claude Code、Codex、Cursor 等)在自动生成、重构或审查 Ktor 项目时输出高质量、可维护的 Kotlin 代码,大幅提升开发效率与一致性。

Everything Claude Code Kotlin Ktor Patterns Skill:Ktor 路由、插件、Koin DI 与 testApplication 测试

在使用 Claude Code 等 AI 编程助手开发 Kotlin Ktor 服务端应用时,很多开发者会遇到路由混乱、插件配置分散、依赖注入不规范、测试覆盖不足等痛点。kotlin-ktor-patterns Skill 正是为了解决这些实际问题而设计,帮助你和 AI 协同高效搭建、维护和测试现代化的 Ktor HTTP 服务。

1. Skill 解决什么问题?

传统手动开发 Ktor 项目常见问题:

  • 路由、插件、认证、序列化等配置杂糅在一起,难以维护
  • 依赖注入写法不统一,Mock/测试困难
  • 错误处理和响应结构不一致,API 体验差
  • 缺乏系统性测试,集成回归难以保障

引入 kotlin-ktor-patterns Skill 后:

  • 项目结构、插件拆分、路由 DSL、Koin 注入、序列化、认证、CORS、错误处理等全部模块化标准化
  • AI 能自动识别并复用最佳实践,生成可测试、易维护的 Ktor 代码
  • 配合 testApplication,轻松实现端到端集成测试
  • 支持 WebSockets、JWT 认证、请求校验等高级场景

适用场景包括:新建/重构 Ktor HTTP 服务、REST API、微服务、WebSockets 实时通信、自动化测试等。

2. 触发条件与常见激活方式

  • 你在 Claude Code、Codex、Cursor 等 AI 编程助手中操作 Ktor 项目时,Skill 会自动激活
  • 明确提出“搭建 Ktor 服务端”、“添加 REST 路由”、“配置 JWT 认证”、“用 Koin 管理依赖”、“写 testApplication 测试”等需求时
  • 代码审查、重构、自动补全、API 设计等场景下,AI 会优先采用本 Skill 的模式

3. 标准项目结构与核心模式

Skill 推荐的 Ktor 项目结构如下:

src/main/kotlin/
├── com/example/
│   ├── Application.kt           # 入口与模块配置
│   ├── plugins/                 # 插件分模块
│   │   ├── Routing.kt
│   │   ├── Serialization.kt
│   │   ├── Authentication.kt
│   │   ├── StatusPages.kt
│   │   └── CORS.kt
│   ├── routes/                  # 路由分模块
│   │   ├── UserRoutes.kt
│   │   ├── AuthRoutes.kt
│   │   └── HealthRoutes.kt
│   ├── models/                  # 数据模型
│   ├── services/                # 业务逻辑
│   ├── repositories/            # 数据访问
│   └── di/                      # Koin 模块
│       └── AppModule.kt
src/test/kotlin/
├── com/example/
│   ├── routes/
│   └── services/

入口配置示例:

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

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

4. Step by Step 使用流程

步骤 1:路由 DSL 组织与插件配置

推荐做法:

  • 路由与插件全部拆分为独立文件,入口 module 只负责汇总调用
  • 路由采用 DSL 组织,分为公开与认证保护两类

示例:

kotlin
// plugins/Routing.kt
fun Application.configureRouting() {
    routing {
        userRoutes()
        authRoutes()
        healthRoutes()
    }
}

// routes/UserRoutes.kt
fun Route.userRoutes() {
    val userService by inject<UserService>()

    route("/users") {
        get { call.respond(userService.getAll()) }
        get("/{id}") { /* ... */ }
        authenticate("jwt") {
            post { /* ... */ }
            put("/{id}") { /* ... */ }
            delete("/{id}") { /* ... */ }
        }
    }
}

步骤 2:内容协商与序列化

  • 推荐使用 kotlinx.serialization,统一 JSON 格式
  • 支持自定义序列化器(如 Instant、LocalDateTime)

示例:

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

步骤 3:JWT 认证与错误处理

  • 认证配置、用户提取、异常处理全部模块化
  • 统一错误响应结构,便于前端消费

认证配置示例:

kotlin
fun Application.configureAuthentication() {
    val jwtSecret = environment.config.property("jwt.secret").getString()
    // ... 省略
    install(Authentication) {
        jwt("jwt") { /* ... */ }
    }
}

错误处理示例:

kotlin
fun Application.configureStatusPages() {
    install(StatusPages) {
        exception<ContentTransformationException> { call, cause ->
            call.respond(HttpStatusCode.BadRequest, ApiResponse.error<Unit>("Invalid request body: ${cause.message}"))
        }
        // ... 其他异常
    }
}

步骤 4:Koin 依赖注入与测试友好

  • 所有 Service/Repository 通过 Koin 单例注册
  • 路由、业务层通过 by inject<T>() 获取依赖
  • 测试时可用 KoinTest/MockK 注入 Mock 实现

Koin 模块示例:

kotlin
val appModule = module {
    single<UserRepository> { ExposedUserRepository(get()) }
    single { UserService(get()) }
    // ...
}
fun Application.configureDI() {
    install(Koin) { modules(appModule) }
}

测试注入示例:

kotlin
class UserServiceTest : FunSpec(), KoinTest {
    override fun extensions() = listOf(KoinExtension(testModule))
    // ...
}

步骤 5:WebSockets 支持

  • Skill 提供 WebSocket 路由、连接管理与消息广播标准写法

示例片段:

kotlin
fun Application.configureWebSockets() {
    install(WebSockets) {
        pingPeriod = 15.seconds
        timeout = 15.seconds
        maxFrameSize = 64 * 1024
    }
}
fun Route.chatRoutes() { /* ... */ }

步骤 6:testApplication 集成测试

  • 推荐用 testApplication + Koin + ContentNegotiation,端到端测试路由和认证
  • 支持模拟 JWT、Mock Service、验证响应结构

测试示例:

kotlin
class UserRoutesTest : FunSpec({
    test("GET /users returns list of users") {
        testApplication {
            application {
                install(Koin) { modules(testModule) }
                configureSerialization()
                configureRouting()
            }
            val response = client.get("/users")
            response.status shouldBe HttpStatusCode.OK
            val body = response.body<ApiResponse<List<UserResponse>>>()
            body.success shouldBe true
        }
    }
})

5. 输出示例

预期 AI 输出片段:

kotlin
// 自动生成的 REST 路由
fun Route.userRoutes() {
    val userService by inject<UserService>()
    route("/users") {
        get { call.respond(ApiResponse.ok(userService.getAll())) }
        authenticate("jwt") {
            post { /* ... */ }
        }
    }
}

自动生成的测试代码:

kotlin
test("POST /users creates a user") {
    testApplication {
        // ... 配置省略
        val response = client.post("/users") {
            contentType(ContentType.Application.Json)
            setBody(CreateUserRequest("Alice", "alice@example.com"))
        }
        response.status shouldBe HttpStatusCode.Created
    }
}

6. 常见配套 Agent 与 Skill 协作

  • Kotlin Reviewer Agent:结合本 Skill,自动审查 Ktor 代码风格、架构分层与安全性(详见 Kotlin Reviewer Agent
  • Kotlin Build Resolver Agent:遇到构建或依赖注入相关错误时,自动修复 Koin/Ktor 配置(详见 Kotlin Build Resolver Agent
  • API Design Skill:与本 Skill 协作,统一 REST API 资源命名、状态码与分页规范(详见 API Design Skill
  • AI Regression Testing Skill:配合 testApplication,自动生成、执行和回归验证 Ktor 路由测试(详见 AI Regression Testing

如需了解 Everything Claude Code 的 Skill/Agent/Hooks 体系全貌,建议参考 Everything Claude Code 完全指南


FAQ

Q: 这个 Skill 支持哪些 Ktor 版本? A: 主要面向 Ktor 2.x,但大部分模式也适用于 Ktor 1.6+,如有特殊版本需求可自定义模板。

Q: 如何让 AI 生成的 Ktor 路由自动带认证和测试? A: 只需明确描述“需要 JWT 保护的路由和 testApplication 测试”,AI 会自动采用本 Skill 的标准写法。

Q: Skill 支持 WebSockets、GraphQL 或 gRPC 吗? A: WebSockets 有完整模式支持,GraphQL/gRPC 可通过扩展 Skill 或结合其他专用 Skill 实现。