我很想更好地了解 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 中的静态内容最好的方法是什么?
这是代码
谢谢
我尝试在本地复制它并使用两种不同的方法使其工作。
- 将其中之一放入静态块中
file("*", "index.html") // single star will only resolve the first part
file("{...}", "index.html") // tailcard will match anything
- 或者,将以下获取处理程序作为您的最后一条路线:
val html = File("index.html").readText()
get("{...}") {
call.respondText(html, ContentType.Text.Html)
}
The {...}
是一个尾卡,匹配任何尚未匹配的请求。
此处提供文档:http://ktor.io/features/routing.html#path
编辑:
对于资源我做了以下工作:
fun Route.staticContent() {
static {
resource("/", "index.html")
resource("*", "index.html")
static("static") {
resources("static")
}
}
}
I can't see your static files in the repository, so here is what it looks like in my project:
![enter image description here](https://i.stack.imgur.com/96njR.png)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)