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…