gpt4 book ai didi

kotlin - Ktor-静态内容路由

转载 作者:行者123 更新时间:2023-12-04 07:53:21 30 4
gpt4 key购买 nike

我想更好地了解Ktor如何处理静态内容的路由。我的静态文件夹(工作目录)中具有以下层次结构:

- static
- index.html
- (some files)
- static
- css (directory)
- js (directory)
- (some files)

我想为他们所有人服务。所以我直接在 routing中使用此代码:
static {
defaultResource("index.html", "static")
resources("static")
}

效果很好,但是问题在于它正在处理所有请求,包括我的小 get:
get("/smoketest"){
call.respondText("smoke test!", ContentType.Text.Plain)
}

一般而言,在Ktor中处理静态内容的最佳方法是什么?

Here is the code

谢谢

最佳答案

我尝试在本地复制它,并使用两种不同的方法使其工作。

  • 将其中之一放入静态块

  • file("*", "index.html") // single star will only resolve the first part

    file("{...}", "index.html") // tailcard will match anything
  • 或者,将以下get处理程序作为最后一条路线:

  • val html = File("index.html").readText()
    get("{...}") {
    call.respondText(html, ContentType.Text.Html)
    }
    {...}是尾卡,可匹配尚未匹配的任何请求。
    可在此处找到文档: http://ktor.io/features/routing.html#path
    编辑:
    对于资源,我做了以下工作:
    fun Route.staticContent() {
    static {
    resource("/", "index.html")
    resource("*", "index.html")
    static("static") {
    resources("static")
    }
    }
    }
    我在存储库中看不到您的静态文件,因此这是我的项目中的样子:
    enter image description here

    关于kotlin - Ktor-静态内容路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901472/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com