Ktor - 静态内容路由
Ktor - Static content routing
我很想更好地了解 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)
}
{...}
是尾卡,匹配任何尚未匹配的请求。
此处提供文档:http://ktor.io/features/routing.html#path
编辑:
对于资源,我做了以下工作:
fun Route.staticContent() {
static {
resource("/", "index.html")
resource("*", "index.html")
static("static") {
resources("static")
}
}
}
我在存储库中看不到你的静态文件,所以它在我的项目中是这样的:
我很想更好地了解 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)
}
{...}
是尾卡,匹配任何尚未匹配的请求。
此处提供文档:http://ktor.io/features/routing.html#path
编辑: 对于资源,我做了以下工作:
fun Route.staticContent() {
static {
resource("/", "index.html")
resource("*", "index.html")
static("static") {
resources("static")
}
}
}
我在存储库中看不到你的静态文件,所以它在我的项目中是这样的: