Skip to content

Latest commit

 

History

History
81 lines (54 loc) · 3.31 KB

Modules.md

File metadata and controls

81 lines (54 loc) · 3.31 KB

Code examples: embedded-server-modules, engine-main-modules

Modules allow you to structure your application by grouping routes.

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.

{src="snippets/engine-main-modules/src/main/kotlin/com/example/Application.kt" include-lines="3-6,9-15"}

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.

Note that plugins installed in a specified module are in effect for other loaded modules.

embeddedServer {id="embedded-server"}

Typically, the embeddedServer function accepts a module implicitly as a lambda argument. You can see the example in the section. You can also extract application logic into a separate module and pass a reference to this module as the module parameter:

{src="snippets/embedded-server-modules/src/main/kotlin/com/example/Application.kt"}

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

Configuration file {id="hocon"}

If you use the application.conf or application.yaml 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.

{src="snippets/engine-main-modules/src/main/kotlin/com/example/Application.kt"}

{src="snippets/engine-main-modules/src/main/kotlin/org/sample/Sample.kt"}

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

{src="snippets/engine-main-modules/src/main/resources/application.conf" include-lines="1,5-10"}

{src="snippets/engine-main-modules/src/main/resources/_application.yaml" include-lines="1,4-8"}

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