Ktor 1.6.4 Help

Modules

Ktor allows you to use modules to structure your application by defining a specific set of routes inside a specific module. A module is an extension function of the Application class. In the example below, the module1 extension function defines a module that accepts GET requests made to the /module1 URL path.

fun Application.module1() { routing { get("/module1") { call.respondText("Hello from 'module1'!") } } }

Loading modules in your application depends on the way used to create a server: in code using the embeddedServer function or by using the application.conf configuration file.

embeddedServer

Typically, the embeddedServer function accepts a module implicitly as a lambda argument. You can see the example in the embeddedServer section.

If you want to load a module defined as an extension function, use one of the ways described below.

Load a single module

To load a single module, pass its name in the module parameter.

package com.example import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* import io.ktor.server.engine.* import io.ktor.server.netty.* fun main() { embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true) } fun Application.module() { routing { get("/module") { call.respondText("Hello from 'module'!") } } }

You can find the full example here: embedded-server-modules.

Load multiple modules

To use multiple modules with embeddedServer, call the required extension functions inside the block.

fun main() { embeddedServer(Netty, port = 8080) { module1() module2() }.start(wait = true) }

HOCON file

If you use the application.conf file to configure a server, you need to specify modules to load using the ktor.application.modules property.

Suppose you have three modules defined in two packages: two modules in the com.example package and one in the org.sample package.

package com.example import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args) fun Application.module1() { routing { get("/module1") { call.respondText("Hello from 'module1'!") } } } fun Application.module2() { routing { get("/module2") { call.respondText("Hello from 'module2'!") } } }
package org.sample import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* fun Application.module3() { routing { get("/module3") { call.respondText("Hello from 'module3'!") } } }

To reference these modules in a configuration file, you need to provide their fully qualified names, separated by a comma. A fully qualified module name includes a fully qualified name of the class and an extension function name.

ktor { application { modules = [ com.example.ApplicationKt.module1, com.example.ApplicationKt.module2, org.sample.SampleKt.module3 ] } }

You can find the full example here: engine-main-modules.

Last modified: 11 October 2021