Ktor - 静态内容路由

Vla*_*lad 10 kotlin ktor

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

- static
 - index.html
 - (some files)
 - static
  - css (directory)
  - js (directory)
  - (some files)
Run Code Online (Sandbox Code Playgroud)

我想为他们所有人服务。所以我直接在routing

static {
  defaultResource("index.html", "static")
  resources("static")
}
Run Code Online (Sandbox Code Playgroud)

效果很好,但问题是它正在处理所有请求,包括我的小请求get

get("/smoketest"){
  call.respondText("smoke test!", ContentType.Text.Plain)
}
Run Code Online (Sandbox Code Playgroud)

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

这是代码

谢谢

And*_*ann 10

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

  1. 将其中之一放在您的静态块中
file("*", "index.html") // single star will only resolve the first part

file("{...}", "index.html") // tailcard will match anything
Run Code Online (Sandbox Code Playgroud)
  1. 或者,将以下 get 处理程序作为您的最后一条路线:
val html = File("index.html").readText()
get("{...}") {
     call.respondText(html, ContentType.Text.Html)
}
Run Code Online (Sandbox Code Playgroud)

{...}是一个尾卡,匹配任何尚未匹配的请求。

此处提供的文档:http : //ktor.io/features/routing.html#path

编辑:对于资源,我做了以下工作:

fun Route.staticContent() {
    static {
        resource("/", "index.html")
        resource("*", "index.html")
        static("static") {
            resources("static")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在存储库中看不到你的静态文件,所以这是我的项目中的样子: 在此处输入图片说明