Several sites on one instance of the Ktor server

Viewed 716

I would like one Ktor application to serve multiple sites. (One site = one domain) I would also like to be able to add and remove sites without restarting the Ktor server.(This is the main question that I cannot solve)

I found such functionality in the documentation, but I don't understand if I can dynamically add new ports? enter image description here

Please tell me if you have any ideas how I can solve my problem?

1 Answers

connector is just a function, so you can call it as many times as you need:

val APPS = mapOf(
    8080 to "Hello from 8080",
    9090 to "Hola desde 9090"
)

fun main() {
    val env = applicationEngineEnvironment {
        module {
            main()
        }
        APPS.forEach {
            connector {
                host = "127.0.0.1"
                port = it.key
            }
        }
    }
    embeddedServer(Netty, env).start(true)
}

fun Application.main() {
    routing {
        get("/") {
            val port = call.request.local.port
            call.respondText(APPS[port] ?: "Who are you?", ContentType.Text.Plain)
        }
    }
}

➜  ~ curl localhost:8080
Hello from 8080
➜  ~ curl localhost:9090
Hola desde 9090

Though if you're only planning to serve HTTP requests it may be a good idea to identify by a host and run apps on the same port:

val APPS = mapOf(
    "first-client.app.local:8080" to "Hello dear first client",
    "second-client.app.local:8080" to "Hola amigo"
)

fun main() {
    val server = embeddedServer(Netty, port = 8080) {
        routing {
            get("/") {
                val host = call.request.headers["HOST"]
                call.respondText(APPS[host] ?: "Who are you?", ContentType.Text.Plain)
            }
        }
    }
    server.start(wait = true)
}

To test locally you need to add these lines to /etc/hosts:

127.0.0.1   first-client.app.local
127.0.0.1   second-client.app.local

And then

➜  ~ curl http://first-client.app.local:8080/
Hello dear first client
➜  ~ curl http://second-client.app.local:8080/
Hola amigo
➜  ~ curl http://localhost:8080/
Who are you?
Related