Hi! How do people use the Application.module exten...
# ktor
g
Hi! How do people use the Application.module extension? Especially using env-variables and shutdown-hooks? Right now we are doing things like this:
Copy code
package com.example.asdf

import io.ktor.routing.routing
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.netty.NettyApplicationEngine
import kotlinx.coroutines.runBlocking
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit

class MyApplication(databaseUrl: String) {
    lateinit var server: NettyApplicationEngine
    val logger = LoggerFactory.getLogger(Application::class.java)
    val databaseService = DatabaseService(databaseUrl)
    val rootEndpoints = RootEndpoints()

    fun start() {
        val serverPort = 8080
        server = embeddedServer(Netty, port = serverPort) {
            routing {
                rootEndpoints.getRoutes(this)
            }
            databaseService.startScanning()
        }.start()
        <http://logger.info|logger.info>("Server started and is listening on $serverPort")
    }

    fun stop() {
        databaseService.stopScanning()
        server.stop(1000, 5000, TimeUnit.MILLISECONDS)
    }
}

fun main() {
    val dbUrl = System.getEnv("DATABASE_URL")
    val application = MyApplication(dbUrl)

    Runtime.getRuntime().addShutdownHook(Thread {
        application.stop()
    })

    application.start()
}
but if I you want to do this in module-fashion, how do people do that? Do I have to initialize my services within the Application.myModule()-fashion?
Copy code
package com.example.asdf

import io.ktor.application.Application
import io.ktor.routing.routing
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import org.slf4j.LoggerFactory

// Should I just consider this as my main-function now?
fun Application.mainModule() {
    // Do I evaluate environment variables in this function now?
    val dbUrl = System.getenv("DATABASE_URL")


    // Should these be initialized here now in this functions local scope?
    val databaseService = DatabaseService(databaseUrl)
    val rootEndpoints = RootEndpoints()

    routing {
        rootEndpoints.getRoutes(this)
    }
    databaseService.startScanning()

    // Where do I put the shutdownHook since I don't have a reference to the server?
    // (server.stop and databaseService.stopScanning)

}

fun main() {
    val logger = LoggerFactory.getLogger(Application::class.java)

    val serverPort = 8080
    val server = embeddedServer(Netty, port = serverPort, module = Application::mainModule).start()
    <http://logger.info|logger.info>("Server started and is listening on $serverPort")
}
t
Did you ever find a solution to this?