0
# Ktor Server Core
1
2
Ktor Server Core provides the essential foundation for building asynchronous web applications and microservices in Kotlin Multiplatform projects. This module includes core server-side functionality with support for routing, request/response handling, application lifecycle management, and a comprehensive plugin architecture. Built with Kotlin coroutines for asynchronous programming, it supports multiple hosting environments and offers a DSL-based configuration approach.
3
4
## Package Information
5
6
- **Package Name**: ktor-server-core-iosarm64
7
- **Package Type**: maven
8
- **Language**: Kotlin
9
- **Platform Target**: iOS ARM64
10
- **Installation**: `implementation("io.ktor:ktor-server-core-iosarm64:3.2.0")`
11
12
## Core Imports
13
14
```kotlin
15
import io.ktor.server.application.*
16
import io.ktor.server.engine.*
17
import io.ktor.server.request.*
18
import io.ktor.server.response.*
19
import io.ktor.server.routing.*
20
```
21
22
## Basic Usage
23
24
```kotlin
25
import io.ktor.server.application.*
26
import io.ktor.server.engine.*
27
import io.ktor.server.response.*
28
import io.ktor.server.routing.*
29
import io.ktor.http.*
30
31
// Create and start an embedded server (requires engine implementation)
32
fun main() {
33
embeddedServer(SomeEngine, port = 8080) {
34
routing {
35
get("/") {
36
call.respondText("Hello, Ktor!")
37
}
38
get("/users/{id}") {
39
val id = call.parameters["id"]
40
call.respondText("User ID: $id")
41
}
42
}
43
}.start(wait = true)
44
}
45
46
// Configure application with plugins
47
fun Application.module() {
48
install(CallLogging)
49
50
routing {
51
route("/api") {
52
get("/health") {
53
call.respond(mapOf("status" to "healthy"))
54
}
55
}
56
}
57
}
58
```
59
60
## Architecture
61
62
Ktor Server Core is built around several key architectural components:
63
64
- **Pipeline-Based Processing**: All request/response handling flows through configurable pipelines with intercept phases
65
- **Plugin System**: Extensible architecture where functionality is added through installable plugins
66
- **DSL Configuration**: Kotlin DSL for declarative configuration of routes, plugins, and application behavior
67
- **Coroutine Integration**: Built-in support for Kotlin coroutines enabling asynchronous, non-blocking operations
68
- **Multiplatform Support**: Common API that works across JVM, JS, and Native targets including iOS ARM64
69
- **Engine Abstraction**: Pluggable server engines (Netty, CIO, etc.) with unified configuration
70
71
## Capabilities
72
73
### Application and Lifecycle Management
74
75
Core application structure, configuration, and lifecycle management. Includes the main Application class, environment setup, and server configuration.
76
77
```kotlin { .api }
78
interface Application {
79
val environment: ApplicationEnvironment
80
val monitor: Events
81
val parentCoroutineContext: CoroutineContext
82
suspend fun disposeAndJoin()
83
}
84
85
interface ApplicationCall : CoroutineScope {
86
val attributes: Attributes
87
val request: ApplicationRequest
88
val response: ApplicationResponse
89
val application: Application
90
val parameters: Parameters
91
suspend fun <T> receiveNullable(typeInfo: TypeInfo): T?
92
suspend fun respond(message: Any?, typeInfo: TypeInfo?)
93
}
94
95
fun serverConfig(block: ServerConfigBuilder.() -> Unit): ServerConfig
96
```
97
98
[Application and Lifecycle Management](./application.md)
99
100
### Configuration Management
101
102
Application configuration system supporting multiple formats and sources with hierarchical merging capabilities.
103
104
```kotlin { .api }
105
interface ApplicationConfig {
106
fun property(path: String): ApplicationConfigValue
107
fun propertyOrNull(path: String): ApplicationConfigValue?
108
fun config(path: String): ApplicationConfig
109
fun configList(path: String): List<ApplicationConfig>
110
fun keys(): Set<String>
111
fun toMap(): Map<String, Any?>
112
}
113
114
interface ApplicationConfigValue {
115
val type: Type
116
fun getString(): String
117
fun getList(): List<String>
118
fun getAs(type: TypeInfo): Any?
119
}
120
121
object ConfigLoader {
122
fun load(path: String? = null): ApplicationConfig
123
}
124
```
125
126
[Configuration Management](./config.md)
127
128
### Server Engines and Embedded Servers
129
130
Application engine abstraction and embedded server functionality for hosting Ktor applications.
131
132
```kotlin { .api }
133
interface ApplicationEngine {
134
val environment: ApplicationEnvironment
135
suspend fun resolvedConnectors(): List<EngineConnectorConfig>
136
fun start(wait: Boolean = false): ApplicationEngine
137
suspend fun startSuspend(wait: Boolean = false): ApplicationEngine
138
fun stop(gracePeriodMillis: Long, timeoutMillis: Long)
139
}
140
141
fun <TEngine : ApplicationEngine, TConfiguration : ApplicationEngine.Configuration>
142
embeddedServer(
143
factory: ApplicationEngineFactory<TEngine, TConfiguration>,
144
port: Int = 80,
145
host: String = "0.0.0.0",
146
watchPaths: List<String> = emptyList(),
147
configure: TConfiguration.() -> Unit = {},
148
module: Application.() -> Unit
149
): EmbeddedServer<TEngine, TConfiguration>
150
```
151
152
[Server Engines and Embedded Servers](./engine.md)
153
154
### Request and Response Handling
155
156
Comprehensive request parsing and response building capabilities with content transformation pipelines.
157
158
```kotlin { .api }
159
interface ApplicationRequest {
160
val call: ApplicationCall
161
val pipeline: ApplicationReceivePipeline
162
val queryParameters: Parameters
163
val headers: Headers
164
val local: RequestConnectionPoint
165
val cookies: RequestCookies
166
}
167
168
interface ApplicationResponse {
169
val call: ApplicationCall
170
val pipeline: ApplicationSendPipeline
171
val headers: ResponseHeaders
172
val cookies: ResponseCookies
173
fun status(): HttpStatusCode?
174
fun status(value: HttpStatusCode)
175
}
176
177
// Extension functions for common operations
178
suspend inline fun <reified T> ApplicationCall.receive(): T
179
suspend fun ApplicationCall.receiveText(): String
180
suspend fun ApplicationCall.respond(message: Any)
181
suspend fun ApplicationCall.respondText(text: String, contentType: ContentType? = null, status: HttpStatusCode? = null)
182
```
183
184
[Request and Response Handling](./request-response.md)
185
186
### Routing System
187
188
Powerful routing DSL with pattern matching, parameter extraction, and nested route organization.
189
190
```kotlin { .api }
191
interface Route {
192
val parent: Route?
193
val selector: RouteSelector
194
val developmentMode: Boolean
195
val environment: ApplicationEnvironment
196
}
197
198
interface RoutingBuilder {
199
fun route(path: String, build: Route.() -> Unit): Route
200
fun method(method: HttpMethod, body: Route.() -> Unit): Route
201
fun handle(body: suspend PipelineContext<Unit, PipelineCall>.() -> Unit)
202
}
203
204
// DSL functions
205
fun Application.routing(configuration: Routing.() -> Unit)
206
fun Route.get(path: String = "", body: suspend PipelineContext<Unit, PipelineCall>.() -> Unit): Route
207
fun Route.post(path: String = "", body: suspend PipelineContext<Unit, PipelineCall>.() -> Unit): Route
208
fun Route.put(path: String = "", body: suspend PipelineContext<Unit, PipelineCall>.() -> Unit): Route
209
fun Route.delete(path: String = "", body: suspend PipelineContext<Unit, PipelineCall>.() -> Unit): Route
210
```
211
212
[Routing System](./routing.md)
213
214
### HTTP Utilities and Extensions
215
216
HTTP-specific utilities, link headers, server push support, and various helper functions.
217
218
```kotlin { .api }
219
// HTTP utilities
220
data class Link(
221
val uri: String,
222
val rel: List<String>,
223
val type: ContentType? = null,
224
val title: String? = null
225
)
226
227
// Extension properties for requests
228
val ApplicationRequest.uri: String
229
val ApplicationRequest.httpMethod: HttpMethod
230
val ApplicationRequest.path: String
231
val ApplicationRequest.host: String
232
val ApplicationRequest.port: Int
233
val ApplicationRequest.contentType: ContentType
234
val ApplicationRequest.userAgent: String?
235
236
// Logging and MDC support
237
interface MDCProvider {
238
fun get(key: String): String?
239
fun put(key: String, value: String?)
240
fun remove(key: String)
241
fun clear()
242
}
243
```
244
245
[HTTP Utilities and Extensions](./utilities.md)
246
247
## Plugin System
248
249
Ktor Server Core includes a comprehensive plugin system for extending functionality:
250
251
### Core Plugin Interfaces
252
253
```kotlin { .api }
254
interface Plugin<TPipeline, TConfiguration, TPlugin> {
255
val key: AttributeKey<TPlugin>
256
fun install(pipeline: TPipeline, configure: TConfiguration.() -> Unit = {}): TPlugin
257
}
258
259
interface ApplicationPlugin<TConfiguration> : BaseApplicationPlugin<Application, TConfiguration, PluginInstance>
260
261
interface RouteScopedPlugin<TConfiguration> : Plugin<RoutingNode, TConfiguration, PluginInstance>
262
```
263
264
### Plugin Creation Functions
265
266
```kotlin { .api }
267
fun createApplicationPlugin(
268
name: String,
269
body: PluginBuilder<Unit>.() -> Unit
270
): ApplicationPlugin<Unit>
271
272
fun <PluginConfigT> createApplicationPlugin(
273
name: String,
274
createConfiguration: () -> PluginConfigT,
275
body: PluginBuilder<PluginConfigT>.() -> Unit
276
): ApplicationPlugin<PluginConfigT>
277
278
fun createRouteScopedPlugin(
279
name: String,
280
body: RouteScopedPluginBuilder<Unit>.() -> Unit
281
): RouteScopedPlugin<Unit>
282
```
283
284
### Plugin Installation
285
286
```kotlin { .api }
287
// Install plugins into application or routes
288
fun <TConfiguration> Application.install(
289
plugin: ApplicationPlugin<TConfiguration>,
290
configure: TConfiguration.() -> Unit = {}
291
): PluginInstance
292
293
fun <TConfiguration> Route.install(
294
plugin: RouteScopedPlugin<TConfiguration>,
295
configure: TConfiguration.() -> Unit = {}
296
): PluginInstance
297
298
// Access installed plugins
299
fun <TConfiguration> Application.plugin(plugin: ApplicationPlugin<TConfiguration>): PluginInstance
300
fun <TConfiguration> Application.pluginOrNull(plugin: ApplicationPlugin<TConfiguration>): PluginInstance?
301
```
302
303
## Core Types
304
305
```kotlin { .api }
306
// Application environment and configuration
307
interface ApplicationEnvironment {
308
val log: Logger
309
val config: ApplicationConfig
310
}
311
312
// Request/Response connection information
313
interface RequestConnectionPoint {
314
val scheme: String
315
val version: String
316
val port: Int
317
val host: String
318
val uri: String
319
val method: HttpMethod
320
val remoteHost: String
321
val userAgent: String?
322
}
323
324
// Parameter collections
325
typealias Parameters = StringValues
326
327
// Pipeline phases and contexts
328
interface PipelineContext<TSubject, TContext>
329
interface PipelineInterceptor<TSubject, TContext>
330
331
// Hook system for plugins
332
interface Hook<HookHandler> {
333
fun install(pipeline: ApplicationCallPipeline, handler: HookHandler)
334
}
335
336
// Event monitoring
337
interface Events {
338
fun <T> subscribe(definition: EventDefinition<T>, handler: suspend (T) -> Unit): EventSubscription<T>
339
fun <T> raise(definition: EventDefinition<T>, value: T)
340
}
341
```