【问题标题】:Ktor - Static content routingKtor - 静态内容路由
【发布时间】:2018-11-26 19:51:55
【问题描述】:

我很想更好地了解 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

谢谢

【问题讨论】:

  • “牵手”是什么意思?
  • 我无法到达这个端点“/smoketest”。我总是重定向到 index.html。感谢您的帮助!
  • 你能发布完整的路由设置吗?另外,您使用的是哪个版本的 ktor?
  • 我已将链接放在帖子末尾。再次感谢您的帮助

标签: kotlin ktor


【解决方案1】:

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

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

file("{...}", "index.html") // tailcard will match anything
  1. 或者,将以下 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")
        }
    }
}

我在存储库中看不到你的静态文件,所以这是我的项目中的样子:

【讨论】:

  • 嗨 Andreas,非常感谢您的快速回答。虽然第一个对我不起作用,但显示 index.html 和第二个是有效的(这是这张尾卡的一个好技巧)。不幸的是,我无论如何都找不到加载我在这个 index.html 中的所有资源(例如 index 级别的 static/js 文件夹中的 js 文件)。您对此有补充代码吗? (您可以再次检查我的代码以查看我的尝试)
  • 我也使用此代码来提供 index.html 中所需的资源:@​​987654328@
  • 非常感谢您的帮助和解答!它就像一个魅力
  • 效果很好。文件夹结构很有帮助!
猜你喜欢
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 2021-11-28
  • 2019-09-19
相关资源
最近更新 更多