or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/maven-io-ktor--ktor-server-core

Ktor Server Core library providing foundational infrastructure for building asynchronous web applications and REST APIs with Kotlin

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/io.ktor/ktor-server-core@3.2.x

To install, run

npx @tessl/cli install tessl/maven-io-ktor--ktor-server-core@3.2.0

0

# Ktor Server Core

1

2

Comprehensive server-side framework for building asynchronous servers and clients in connected systems using Kotlin coroutines. Ktor Server Core provides the foundational infrastructure for creating web applications and REST APIs with built-in support for routing, request/response handling, content negotiation, and plugin architecture.

3

4

## Package Information

5

6

- **Package:** `io.ktor:ktor-server-core`

7

- **Type:** Kotlin Multiplatform Library

8

- **Language:** Kotlin

9

- **Installation:** Add dependency to your `build.gradle.kts`

10

11

```kotlin { .api }

12

dependencies {

13

implementation("io.ktor:ktor-server-core:$ktor_version")

14

}

15

```

16

17

## Core Imports

18

19

```kotlin { .api }

20

// Core application and server functionality

21

import io.ktor.server.application.*

22

import io.ktor.server.engine.*

23

import io.ktor.server.routing.*

24

import io.ktor.server.request.*

25

import io.ktor.server.response.*

26

import io.ktor.server.config.*

27

28

// HTTP utilities and content handling

29

import io.ktor.http.*

30

import io.ktor.server.plugins.*

31

```

32

33

## Basic Usage

34

35

### Creating an Embedded Server

36

37

```kotlin { .api }

38

import io.ktor.server.engine.*

39

import io.ktor.server.netty.*

40

41

fun main() {

42

embeddedServer(Netty, port = 8080) {

43

routing {

44

get("/") {

45

call.respondText("Hello, Ktor!")

46

}

47

}

48

}.start(wait = true)

49

}

50

```

51

52

### Application Configuration

53

54

```kotlin { .api }

55

fun main() {

56

val server = embeddedServer(Netty, port = 8080) {

57

install(Routing)

58

59

routing {

60

get("/health") {

61

call.respondText("OK")

62

}

63

}

64

}

65

66

server.start(wait = true)

67

}

68

```

69

70

## Architecture

71

72

Ktor Server Core follows a pipeline-based architecture with several key components:

73

74

### Application Pipeline

75

The `ApplicationCallPipeline` processes incoming requests through phases:

76

- **Setup** - Initial request setup and validation

77

- **Monitoring** - Metrics and monitoring hooks

78

- **Plugins** - Plugin execution (authentication, content negotiation, etc.)

79

- **Call** - Main request processing

80

- **Fallback** - Error handling and fallback responses

81

82

### Plugin System

83

Ktor uses a powerful plugin architecture where functionality is added through installable plugins. Each plugin can intercept and modify the request/response pipeline.

84

85

### Server Engines

86

Multiple engine implementations support different deployment scenarios:

87

- **Netty** - High-performance NIO-based engine

88

- **Jetty** - Traditional servlet container

89

- **CIO** - Kotlin coroutine-based engine

90

- **Tomcat** - Traditional servlet container

91

92

## Capabilities

93

94

### Application Lifecycle and Plugin Management

95

[Application Management](./application.md)

96

97

Manage application lifecycle, install and configure plugins, and handle application events.

98

99

```kotlin { .api }

100

// Application creation and configuration

101

fun Application.module() {

102

install(ContentNegotiation) {

103

json()

104

}

105

106

monitor.subscribe(ApplicationStarted) { application ->

107

application.log.info("Application started")

108

}

109

}

110

111

// Plugin installation and access

112

val plugin = application.plugin(ContentNegotiation)

113

val pluginOrNull = application.pluginOrNull(SomePlugin)

114

```

115

116

### Routing and URL Handling

117

[Routing System](./routing.md)

118

119

Define URL routes, handle different HTTP methods, and capture path parameters.

120

121

```kotlin { .api }

122

routing {

123

// HTTP method routes

124

get("/users") { call.respond(users) }

125

post("/users") { /* create user */ }

126

127

// Path parameters

128

get("/users/{id}") {

129

val userId = call.parameters["id"]

130

call.respond(getUserById(userId))

131

}

132

133

// Route groups

134

route("/api/v1") {

135

get("/status") { call.respondText("API v1 OK") }

136

}

137

}

138

```

139

140

### Request and Response Processing

141

[Request/Response Handling](./request-response.md)

142

143

Handle incoming requests, process content, and send responses with proper content types.

144

145

```kotlin { .api }

146

// Request processing

147

get("/upload") {

148

val content = call.receive<String>()

149

val contentType = call.request.contentType()

150

val headers = call.request.headers

151

152

call.respondText("Received: $content")

153

}

154

155

// Response generation

156

post("/api/data") {

157

val data = processRequest()

158

call.respond(HttpStatusCode.Created, data)

159

}

160

```

161

162

### Server Engine Configuration

163

[Server Engines](./engine.md)

164

165

Configure and start server engines, manage connectors, and handle deployment scenarios.

166

167

```kotlin { .api }

168

// Embedded server with custom configuration

169

val server = embeddedServer(

170

factory = Netty,

171

host = "0.0.0.0",

172

port = 8080,

173

configure = {

174

// Engine-specific configuration

175

connectionGroupSize = 2

176

workerGroupSize = 5

177

callGroupSize = 10

178

}

179

) {

180

// Application configuration

181

module()

182

}

183

```

184

185

### Configuration Management

186

[Configuration System](./configuration.md)

187

188

Load and manage application configuration from various sources including files, environment variables, and command line arguments.

189

190

```kotlin { .api }

191

// Configuration loading

192

val config = applicationEnvironment {

193

config = HoconApplicationConfig(ConfigFactory.load())

194

}

195

196

// Configuration access

197

val port = config.config("server").property("port").getString().toInt()

198

val environment = config.propertyOrNull("environment")?.getString() ?: "development"

199

```

200

201

## Key Types and Interfaces

202

203

### Core Application Types

204

205

```kotlin { .api }

206

// Main application class

207

class Application internal constructor(

208

environment: ApplicationEnvironment,

209

developmentMode: Boolean,

210

rootPath: String,

211

monitor: Events,

212

parentCoroutineContext: CoroutineContext,

213

engineProvider: () -> ApplicationEngine

214

) : ApplicationCallPipeline, CoroutineScope {

215

val engine: ApplicationEngine

216

val rootPath: String

217

val monitor: Events

218

suspend fun disposeAndJoin()

219

}

220

221

// Base application call interface

222

interface ApplicationCall : CoroutineScope {

223

val attributes: Attributes

224

val request: ApplicationRequest

225

val response: ApplicationResponse

226

val application: Application

227

val parameters: Parameters

228

229

suspend fun <T> receiveNullable(typeInfo: TypeInfo): T?

230

suspend fun respond(message: Any?, typeInfo: TypeInfo?)

231

}

232

233

// Main pipeline call interface (extends ApplicationCall)

234

interface PipelineCall : ApplicationCall {

235

override val request: PipelineRequest

236

override val response: PipelineResponse

237

}

238

```

239

240

### Plugin System Types

241

242

```kotlin { .api }

243

// Base plugin interface

244

interface Plugin<

245

in TPipeline : Pipeline<*, PipelineCall>,

246

out TConfiguration : Any,

247

TPlugin : Any

248

> {

249

val key: AttributeKey<TPlugin>

250

fun install(pipeline: TPipeline, configure: TConfiguration.() -> Unit): TPlugin

251

}

252

253

// Base application plugin interface

254

interface BaseApplicationPlugin<

255

in TPipeline : Pipeline<*, PipelineCall>,

256

out TConfiguration : Any,

257

TPlugin : Any

258

> : Plugin<TPipeline, TConfiguration, TPlugin>

259

260

// Application plugin interface

261

interface ApplicationPlugin<out TConfiguration : Any> :

262

BaseApplicationPlugin<Application, TConfiguration, PluginInstance>

263

264

// Plugin installation and access

265

fun <A : Pipeline<*, PipelineCall>, F : Any> A.plugin(plugin: Plugin<*, *, F>): F

266

fun <A : Pipeline<*, PipelineCall>, F : Any> A.pluginOrNull(plugin: Plugin<*, *, F>): F?

267

```

268

269

### Engine and Server Types

270

271

```kotlin { .api }

272

// Application engine interface

273

interface ApplicationEngine {

274

val environment: ApplicationEnvironment

275

fun start(wait: Boolean = false): ApplicationEngine

276

suspend fun startSuspend(wait: Boolean = false): ApplicationEngine

277

fun stop(gracePeriodMillis: Long = 500, timeoutMillis: Long = 500)

278

suspend fun resolvedConnectors(): List<EngineConnectorConfig>

279

}

280

281

// Server configuration

282

data class ServerConfig(

283

val environment: ApplicationEnvironment,

284

val rootPath: String = "",

285

val developmentMode: Boolean = false,

286

val parentCoroutineContext: CoroutineContext? = null

287

)

288

```

289

290

## Error Handling

291

292

Ktor provides structured error handling with specific exception types:

293

294

```kotlin { .api }

295

// HTTP exceptions

296

class NotFoundException(message: String? = "Not Found") : Exception(message)

297

class MissingRequestParameterException(parameterName: String) : Exception()

298

class ParameterConversionException(

299

parameterName: String,

300

type: String,

301

cause: Throwable? = null

302

) : Exception()

303

304

// Plugin exceptions

305

class DuplicatePluginException(key: String) : Exception()

306

class MissingApplicationPluginException(key: AttributeKey<*>) : Exception()

307

```

308

309

## Event System

310

311

Application lifecycle events for monitoring and hooks:

312

313

```kotlin { .api }

314

// Application events

315

object ApplicationStarting : EventDefinition<Application>()

316

object ApplicationStarted : EventDefinition<Application>()

317

object ServerReady : EventDefinition<ApplicationEngine>()

318

object ApplicationStopping : EventDefinition<Application>()

319

object ApplicationStopped : EventDefinition<Application>()

320

321

// Event subscription

322

application.monitor.subscribe(ApplicationStarted) { app ->

323

app.log.info("Application has started successfully")

324

}

325

```

326

327

## Additional Utilities

328

329

### Exception Classes

330

331

```kotlin { .api }

332

// Standard HTTP exceptions from io.ktor.server.plugins

333

class NotFoundException(message: String? = "Not Found") : Exception(message)

334

class MissingRequestParameterException(parameterName: String) : Exception()

335

class ParameterConversionException(

336

parameterName: String,

337

type: String,

338

cause: Throwable? = null

339

) : Exception()

340

class CannotTransformContentToTypeException(type: TypeInfo) : Exception()

341

class UnsupportedMediaTypeException(contentType: ContentType) : Exception()

342

class PayloadTooLargeException(message: String) : Exception()

343

```

344

345

### Utility Classes

346

347

```kotlin { .api }

348

// Thread-safe utilities from io.ktor.server.util

349

class CopyOnWriteHashMap<K, V> : MutableMap<K, V>

350

interface Parameters : StringValues

351

352

// Path utilities

353

fun normalizePathComponents(components: List<String>): List<String>

354

355

// URL building utilities

356

fun URLBuilder.createFromCall(call: ApplicationCall): URLBuilder

357

fun url(block: URLBuilder.() -> Unit): String

358

```

359

360

### HTTP Utilities

361

362

```kotlin { .api }

363

// HTTP content and status utilities from io.ktor.server.http

364

class HttpStatusCodeContent(

365

val statusCode: HttpStatusCode,

366

val message: String

367

)

368

369

// Link header utilities

370

object LinkHeader {

371

fun parse(value: String): List<LinkHeaderValue>

372

fun render(links: List<LinkHeaderValue>): String

373

}

374

375

// HTTP/2 Push support

376

object Push {

377

fun buildPushPromise(call: ApplicationCall, block: ResponsePushBuilder.() -> Unit)

378

}

379

```

380

381

### Logging Support

382

383

```kotlin { .api }

384

// Logging utilities from io.ktor.server.logging

385

class Logging {

386

companion object {

387

fun configure(level: Level, appenders: List<String>)

388

}

389

}

390

391

// MDC (Mapped Diagnostic Context) provider

392

interface MDCProvider {

393

fun withMDCBlock(block: () -> Unit)

394

fun put(key: String, value: String?)

395

fun get(key: String): String?

396

fun clear()

397

}

398

```

399

400

This documentation provides comprehensive coverage of Ktor Server Core functionality. Use the linked sub-documents for detailed information about specific capabilities and advanced usage patterns.