Ktor - Server

Introduction

Ktor is built on Corutina and lets you use only what you need while structuring your application your way. You can also extend Ktor with your own plugins easily.

Project setup

Generate a “Ktor server application” with Amper.

Two files are created under src: Application.kt and Routing.kt.

Run the project:

Open http://localhost:8080 to confirm it’s running.

You should see “Hello World!”:

Server

EngineMain starts a server with the selected engine and loads application modules from the external configuration file application.yaml, typically located in the resource directory.

src/Application.kt
import io.ktor.server.application.*
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
fun Application.module() {
configureRouting()
}

In addition to specifying which modules to load, the configuration file can include various server parameters such as the port, host, and SSL settings.

In this link you can find the full list of parameters: Server Configuration

Amper

To enable Ktor support, you add the following to the module.yaml file:

settings:
ktor: enabled

Setting ktor: enabled performs the following actions:

  • Applies Ktor BOM
  • Contributes Ktor-related entries to a built-in library catalog
  • Adds the io.ktor.development=true system property when running the app with amper run

You can also customize the version of the Ktor libraries using the full form of the configuration:

settings:
ktor:
enabled: true
version: 3.3.2

Autoreload

Restarting a server during development can be slow. Ktor supports auto-reload to speed up the feedback loop:

resources/application.yaml
ktor:
development: true

Not working 🤨: Auto-reload

Plugins

A typical request/response pipeline in Ktor looks like the following:

Request

Routing

App logic

Response

It starts with a request, which is routed to a specific handler, processed by our application logic, and finally responded to.

Many applications require common functionality out of the scope of the application logic. This could be things like serialization and content encoding, compression, headers, cookie support, etc. All of these are provided in Ktor by what we call Plugins.

If we look at the previous pipeline diagram, Plugins sit between the request/response and the application logic:

As a request comes in:

  • It is routed to the correct handler via the routing mechanism
  • before being handed off to the handler, it goes through one or more Plugins
  • the handler (application logic) handles the request
  • before the response is sent to the client, it goes through one or more Plugins

Server Plugins