将 index.html 作为 Akka HTTP 的 getFromDirectory 中的默认文件 [英] Treat index.html as default file in Akka HTTP's getFromDirectory
问题描述
假设我有一个文件夹 foo
,其中包含一个 index.html
文件,以及下面用于 Akka HTTP 的以下最小(但很可能不起作用)服务器代码:
Assuming I have a folder foo
with an index.html
file in it and the following minimal (but most likely not functional) server code for Akka HTTP below:
object Server extends App {
val route: Route =
pathPrefix("foo") {
getFromDirectory("foo")
}
Http().bindAndHandle(route, "0.0.0.0", 8080)
}
如果我在浏览器中打开 http://localhost:8080/foo/index.html
将正确提供
index.html
,但如果我打开 <代码>http://localhost:8080/foo 或 http://localhost:8080/foo/
.
index.html
will correctly be served if I open http://localhost:8080/foo/index.html
in a browser, but not if I open http://localhost:8080/foo
or http://localhost:8080/foo/
.
如果这是可能的,我如何设置我的 Akka HTTP 路由以默认在该位置提供 index.html
文件?
If this is even possible, how can I set up my Akka HTTP routes to serve index.html
files within that location by default?
我知道我可以做到以下几点:
I know I could do the following:
val route: Route =
path("foo") {
getFromFile("foo/index.html")
} ~
pathPrefix("foo") {
getFromDirectory("foo")
}
但是:
- 这只会使
http://localhost:8080/foo
工作,而不是http://localhost:8080/foo/
- 这是非常临时的,并不适用于全局:如果我有一个
foo/bar/index.html
文件,问题将是相同的.
- This only makes
http://localhost:8080/foo
work, nothttp://localhost:8080/foo/
- This is very ad-hoc and does not apply globally: if I have a
foo/bar/index.html
file, the problem will be the same.
推荐答案
您可以使用 pathEndOrSingleSlash
指令创建您正在寻找的 Route
指令:
You can create the Route
you are looking for by using the pathEndOrSingleSlash
Directive:
val route =
pathPrefix("foo") {
pathEndOrSingleSlash {
getFromFile("foo/index.html")
} ~
getFromDirectory("foo")
}
此路由将在路径的末尾匹配并提供 index.html,或者如果末尾不匹配,它将调用 getFromDirectory.
This Route will match at the end of the path and feed up the index.html, or if the end doesn't match it will call getFromDirectory instead.
如果你想让这个全局",你可以用它创建一个函数:
If you want to make this "global" you can make a function out of it:
def routeAsDir[T](pathMatcher : PathMatcher[T], dir : String) : Route =
pathPrefix(pathMatcher) {
pathEndOrSingleSlash {
getFromFile(dir + "/index.html")
} ~
getFromDirectory(dir)
}
然后可以使用
val barRoute = routeAsDir("foo" / "bar", "foo/bar")
函数式 Akka Http
旁注:您的代码完全正常运行.Directives DSL 的优雅可能会误导您,并让您相信您不小心误入了命令式编程风格.但每条指令都只是一个功能;没有比这更实用"的了...
Side note: your code is completely functional. The elegance of the Directives DSL can be a bit misleading and convince you that you've accidentally strayed back into imperative programming style. But each of the Directives is simply a function; can't get more "functional" than that...
这篇关于将 index.html 作为 Akka HTTP 的 getFromDirectory 中的默认文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!