What is an Application?

A Ktor Server Application is a custom program listening to one or more ports using a configured server engine,composed by modules with the application logic, that install features, like routing,sessions, compression, etc. to handle HTTP/S 1.x/2.x and WebSocket requests.

Ktor also provides functionality to handle raw sockets, but not as part of the Application andits pipeline.

Table of contents:

Application

An Application instance is the main unit of a Ktor Application. When a request comes in(a request can be HTTP, HTTP/2 or WebSocket requests), it is converted to an ApplicationCalland goes through a pipeline which is owned by the Application. The pipeline consists of one or moreinterceptors that are previously installed, providing certain functionality such as routing,compression, etc. that ends handling the request.

Normally, a Ktor program configures the Application pipeline through modulesthat install and configure features.

You can read further information about the pipeline, in the lifecycle section.

ApplicationCall

Check the dedicated page about ApplicationCall.

Features

A feature is a singleton (usually a companion object) that you can install and configure for a pipeline.Ktor includes some standard features, but you can add your own or other features from the community. You can install features in any pipeline, like the application itself, or specific routes.

You can read more about features in its dedicated page.

Modules

A Ktor module is just a user-defined function receiving the Application class that is in charge of configuringthe server pipeline, install features, registering routes, handling requests, etc.

You have to specify the modules to load when the server starts in the application.conf file.

A simple module function would look like this:

Main.kt

  1. package com.example.myapp
  2. fun Application.mymodule() {
  3. routing {
  4. get("/") {
  5. call.respondText("Hello World!")
  6. }
  7. }
  8. }

Of course, you can split the module function in several smaller functions or classes.

Modules are referenced by their fully qualified name: the fully qualified name of the class and the method name,separated by a dot (.).

So for the example, the module’s fully qualified name would be:

  1. com.example.myapp.MainKt.mymodule

mymodule is an extension method of the class Application (where Application is the receiver).Since it is defined as a top-level function, Kotlin creates a JVM class with a Kt suffix (FileNameKt),and adds the extension method as a static method with the receiver as its first parameter.In this case, the class name is MainKt in the com.example.myapp package, and the Java method signature would bestatic public void mymodule(Application app).

What’s next