Ktor-静态内容路由 [英] Ktor - Static content routing
问题描述
我想更好地了解Ktor如何处理静态内容的路由.我的静态文件夹(工作目录)中具有以下层次结构:
I would love to understand better how Ktor is handling the routing for static content. I have the following hierarchy in my static folder (working directory):
- static
- index.html
- (some files)
- static
- css (directory)
- js (directory)
- (some files)
我想为所有人提供服务.所以我直接在routing
中使用此代码:
I'd like to serve all of them. So I was using directly this code in routing
:
static {
defaultResource("index.html", "static")
resources("static")
}
效果很好,但是问题在于它可以处理所有请求,包括我的小get
:
Which works very well, but the issue is that it's taking the hand on all requests including my small get
:
get("/smoketest"){
call.respondText("smoke test!", ContentType.Text.Plain)
}
一般来说,在Ktor中处理静态内容的最佳方法是什么?
What would be the best to handle in general the static content in Ktor?
推荐答案
我尝试在本地复制它,并使其以两种不同的方式工作.
I tried reproducing it locally and made it work with two different approaches.
- 将其中之一放入您的静态块中
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)
}
val html = File("index.html").readText()
get("{...}") {
call.respondText(html, ContentType.Text.Html)
}
{...}
是一张尾卡,可以匹配尚未匹配的任何请求.
The {...}
is a tailcard and matches any request that hasn't been matched yet.
可在此处找到文档: http://ktor.io/features/routing.html#path
对于资源,我做了以下工作:
For resources I made the following work:
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:
这篇关于Ktor-静态内容路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!