【问题标题】:Treat index.html as default file in Akka HTTP's getFromDirectory将 index.html 视为 Akka HTTP 的 getFromDirectory 中的默认文件
【发布时间】:2017-03-18 06:03:58
【问题描述】:

假设我有一个文件夹 foo,其中有一个 index.html 文件,下面是 Akka HTTP 的以下最小(但很可能不起作用)服务器代码:

object Server extends App {
  val route: Route =
    pathPrefix("foo") {
      getFromDirectory("foo")
    }

  Http().bindAndHandle(route, "0.0.0.0", 8080)
}

如果我在浏览器中打开http://localhost:8080/foo/index.htmlindex.html 将正确提供,但如果我打开http://localhost:8080/foohttp://localhost:8080/foo/,则不会。

如果可能的话,我如何设置我的 Akka HTTP 路由以默认在该位置提供 index.html 文件?

我知道我可以做到以下几点:

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 文件,问题将是相同的。

【问题讨论】:

    标签: scala akka-http


    【解决方案1】:

    您可以使用pathEndOrSingleSlash 指令创建您正在寻找的Route

    val route =
      pathPrefix("foo") {
        pathEndOrSingleSlash {
          getFromFile("foo/index.html")
        } ~ 
        getFromDirectory("foo")
      }
    

    此路由将匹配路径的末尾并提供 index.html,或者如果末尾不匹配,它将改为调用 getFromDirectory。

    如果你想让这个“全局”,你可以用它做一个函数:

    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 的优雅可能会有点误导,并让您相信您不小心回到了命令式编程风格。但是每个指令都只是一个函数;没有比这更“实用”的了......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 2019-06-23
      • 2016-03-28
      • 1970-01-01
      相关资源
      最近更新 更多