or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

application.mdconfiguration.mdengine.mdindex.mdrequest-response.mdrouting.md
tile.json

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

index.mddocs/

Ktor Server Core

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.

Package Information

  • Package: io.ktor:ktor-server-core
  • Type: Kotlin Multiplatform Library
  • Language: Kotlin
  • Installation: Add dependency to your build.gradle.kts
dependencies {
    implementation("io.ktor:ktor-server-core:$ktor_version")
}

Core Imports

// Core application and server functionality
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.routing.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.config.*

// HTTP utilities and content handling
import io.ktor.http.*
import io.ktor.server.plugins.*

Basic Usage

Creating an Embedded Server

import io.ktor.server.engine.*
import io.ktor.server.netty.*

fun main() {
    embeddedServer(Netty, port = 8080) {
        routing {
            get("/") {
                call.respondText("Hello, Ktor!")
            }
        }
    }.start(wait = true)
}

Application Configuration

fun main() {
    val server = embeddedServer(Netty, port = 8080) {
        install(Routing)
        
        routing {
            get("/health") {
                call.respondText("OK")
            }
        }
    }
    
    server.start(wait = true)
}

Architecture

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

Application Pipeline

The ApplicationCallPipeline processes incoming requests through phases:

  • Setup - Initial request setup and validation
  • Monitoring - Metrics and monitoring hooks
  • Plugins - Plugin execution (authentication, content negotiation, etc.)
  • Call - Main request processing
  • Fallback - Error handling and fallback responses

Plugin System

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

Server Engines

Multiple engine implementations support different deployment scenarios:

  • Netty - High-performance NIO-based engine
  • Jetty - Traditional servlet container
  • CIO - Kotlin coroutine-based engine
  • Tomcat - Traditional servlet container

Capabilities

Application Lifecycle and Plugin Management

Application Management

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

// Application creation and configuration
fun Application.module() {
    install(ContentNegotiation) {
        json()
    }
    
    monitor.subscribe(ApplicationStarted) { application ->
        application.log.info("Application started")
    }
}

// Plugin installation and access
val plugin = application.plugin(ContentNegotiation)
val pluginOrNull = application.pluginOrNull(SomePlugin)

Routing and URL Handling

Routing System

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

routing {
    // HTTP method routes
    get("/users") { call.respond(users) }
    post("/users") { /* create user */ }
    
    // Path parameters
    get("/users/{id}") {
        val userId = call.parameters["id"]
        call.respond(getUserById(userId))
    }
    
    // Route groups
    route("/api/v1") {
        get("/status") { call.respondText("API v1 OK") }
    }
}

Request and Response Processing

Request/Response Handling

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

// Request processing
get("/upload") {
    val content = call.receive<String>()
    val contentType = call.request.contentType()
    val headers = call.request.headers
    
    call.respondText("Received: $content")
}

// Response generation
post("/api/data") {
    val data = processRequest()
    call.respond(HttpStatusCode.Created, data)
}

Server Engine Configuration

Server Engines

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

// Embedded server with custom configuration
val server = embeddedServer(
    factory = Netty,
    host = "0.0.0.0", 
    port = 8080,
    configure = {
        // Engine-specific configuration
        connectionGroupSize = 2
        workerGroupSize = 5
        callGroupSize = 10
    }
) {
    // Application configuration
    module()
}

Configuration Management

Configuration System

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

// Configuration loading
val config = applicationEnvironment {
    config = HoconApplicationConfig(ConfigFactory.load())
}

// Configuration access
val port = config.config("server").property("port").getString().toInt()
val environment = config.propertyOrNull("environment")?.getString() ?: "development"

Key Types and Interfaces

Core Application Types

// Main application class
class Application internal constructor(
    environment: ApplicationEnvironment,
    developmentMode: Boolean,
    rootPath: String,
    monitor: Events,
    parentCoroutineContext: CoroutineContext,
    engineProvider: () -> ApplicationEngine
) : ApplicationCallPipeline, CoroutineScope {
    val engine: ApplicationEngine
    val rootPath: String
    val monitor: Events
    suspend fun disposeAndJoin()
}

// Base application call interface
interface ApplicationCall : CoroutineScope {
    val attributes: Attributes
    val request: ApplicationRequest
    val response: ApplicationResponse
    val application: Application
    val parameters: Parameters
    
    suspend fun <T> receiveNullable(typeInfo: TypeInfo): T?
    suspend fun respond(message: Any?, typeInfo: TypeInfo?)
}

// Main pipeline call interface (extends ApplicationCall)
interface PipelineCall : ApplicationCall {
    override val request: PipelineRequest
    override val response: PipelineResponse
}

Plugin System Types

// Base plugin interface
interface Plugin<
    in TPipeline : Pipeline<*, PipelineCall>,
    out TConfiguration : Any,
    TPlugin : Any
> {
    val key: AttributeKey<TPlugin>
    fun install(pipeline: TPipeline, configure: TConfiguration.() -> Unit): TPlugin
}

// Base application plugin interface
interface BaseApplicationPlugin<
    in TPipeline : Pipeline<*, PipelineCall>,
    out TConfiguration : Any,
    TPlugin : Any
> : Plugin<TPipeline, TConfiguration, TPlugin>

// Application plugin interface
interface ApplicationPlugin<out TConfiguration : Any> :
    BaseApplicationPlugin<Application, TConfiguration, PluginInstance>

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

Engine and Server Types

// Application engine interface
interface ApplicationEngine {
    val environment: ApplicationEnvironment
    fun start(wait: Boolean = false): ApplicationEngine
    suspend fun startSuspend(wait: Boolean = false): ApplicationEngine
    fun stop(gracePeriodMillis: Long = 500, timeoutMillis: Long = 500)
    suspend fun resolvedConnectors(): List<EngineConnectorConfig>
}

// Server configuration
data class ServerConfig(
    val environment: ApplicationEnvironment,
    val rootPath: String = "",
    val developmentMode: Boolean = false,
    val parentCoroutineContext: CoroutineContext? = null
)

Error Handling

Ktor provides structured error handling with specific exception types:

// HTTP exceptions
class NotFoundException(message: String? = "Not Found") : Exception(message)
class MissingRequestParameterException(parameterName: String) : Exception()
class ParameterConversionException(
    parameterName: String, 
    type: String, 
    cause: Throwable? = null
) : Exception()

// Plugin exceptions  
class DuplicatePluginException(key: String) : Exception()
class MissingApplicationPluginException(key: AttributeKey<*>) : Exception()

Event System

Application lifecycle events for monitoring and hooks:

// Application events
object ApplicationStarting : EventDefinition<Application>()
object ApplicationStarted : EventDefinition<Application>()
object ServerReady : EventDefinition<ApplicationEngine>()
object ApplicationStopping : EventDefinition<Application>()
object ApplicationStopped : EventDefinition<Application>()

// Event subscription
application.monitor.subscribe(ApplicationStarted) { app ->
    app.log.info("Application has started successfully")
}

Additional Utilities

Exception Classes

// Standard HTTP exceptions from io.ktor.server.plugins
class NotFoundException(message: String? = "Not Found") : Exception(message)
class MissingRequestParameterException(parameterName: String) : Exception()
class ParameterConversionException(
    parameterName: String, 
    type: String, 
    cause: Throwable? = null
) : Exception()
class CannotTransformContentToTypeException(type: TypeInfo) : Exception()
class UnsupportedMediaTypeException(contentType: ContentType) : Exception()
class PayloadTooLargeException(message: String) : Exception()

Utility Classes

// Thread-safe utilities from io.ktor.server.util
class CopyOnWriteHashMap<K, V> : MutableMap<K, V>
interface Parameters : StringValues

// Path utilities
fun normalizePathComponents(components: List<String>): List<String>

// URL building utilities
fun URLBuilder.createFromCall(call: ApplicationCall): URLBuilder
fun url(block: URLBuilder.() -> Unit): String

HTTP Utilities

// HTTP content and status utilities from io.ktor.server.http
class HttpStatusCodeContent(
    val statusCode: HttpStatusCode,
    val message: String
)

// Link header utilities
object LinkHeader {
    fun parse(value: String): List<LinkHeaderValue>
    fun render(links: List<LinkHeaderValue>): String
}

// HTTP/2 Push support
object Push {
    fun buildPushPromise(call: ApplicationCall, block: ResponsePushBuilder.() -> Unit)
}

Logging Support

// Logging utilities from io.ktor.server.logging
class Logging {
    companion object {
        fun configure(level: Level, appenders: List<String>)
    }
}

// MDC (Mapped Diagnostic Context) provider
interface MDCProvider {
    fun withMDCBlock(block: () -> Unit)
    fun put(key: String, value: String?)
    fun get(key: String): String?
    fun clear()
}

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.