Ktor - 以编程方式创建多个子域

Ktor - Create Multiple Subdomains Programatically

好吧,这听起来像是一个愚蠢的问题,但我真的需要知道,有没有一种方法可以使用 Ktor 以编程方式创建多个域。例如,假设我有一个域:example.com

现在我需要后端服务器上的逻辑为在我的网站上注册的每个用户创建一个新的子域。例如,当 John 注册时,我希望能够立即创建一个新的子域: john.example.com 。现在我不确定这可以实现什么以及如何实现,这就是为什么我在这里询问一些方向?

如果这太复杂,那么有没有办法在我的网站上的每个用户注册后从代码动态创建多个端点,例如:示例。com/John ?

有什么好的资源可以让我阅读吗?

在Ktor端,你可以在服务器启动后动态添加路由,并使用host路由生成器来匹配请求的主机。此外,您需要像@Stephen Jennings 所说的那样以编程方式添加 DNS 条目。这是一个示例,其中 5 秒后添加了主机 john.example.com 的路由。您可以使用 /etc/hosts 文件中的条目 127.0.0.1 john.example.com 在本地测试它。

import io.ktor.application.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.coroutines.*

fun main() {
    val server = embeddedServer(Netty, port = 4444) {
        routing {
            get("/example") {
                call.respondText { "example" }
            }
        }
    }

    server.start(wait = false)

    CoroutineScope(Dispatchers.IO).launch {
        delay(5000)
        val routing = server.application.feature(Routing)
        routing.addRoutesForHost("john.example.com")
    }
}

fun Route.addRoutesForHost(host: String) {
    host(host) {
        get("/hello") {
            call.respondText { "Hello ${call.request.headers[HttpHeaders.Host]}" }
        }
    }
}