getFromDirectory 在 akka-http 路由中不起作用

getFromDirectory not working in a akka-http route

我有一个文件夹 root,其中包含 index.html 和其他资源,例如 .css 文件。

现在,我正在尝试使用下面的 akka-http 路由 (myRoute) 在 localhost:8080/test 托管此文件夹。此外,我想在 localhost:8080 托管一个 hello-world 页面。我还希望带有尾部斜线的 URI 重定向到非斜线 URI(localhost:8080/test 应该等于 localhost:8080/test/)。

不知怎么的,我无法做到这一点。 hello-world 页面工作正常,但文件夹未托管。我得到的只是一条 The requested resource could not be found. 消息(在 Chrome 中)。

def route: Route = {
  redirectToNoTrailingSlashIfPresent(StatusCodes.Found) {
    (pathSingleSlash {
      get {
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, homeHtml)) // "hello world"
      }
    }
    ~
      pathPrefix("test") {
           getFromDirectory("root") // contains the index.html
    })
  }
}

编辑:

当我尝试使用 getFromFile(webDir + "/index.html") 而不是 getFromDirectory(webDir)webDirroot)时,index.html 已加载但无法访问 css/js 文件。

我已将 redirectToTrailingSlashIfMissing 移动到内部指令。它似乎做你想要的。请注意 webdir 是带有 index.html

的文件夹的绝对路径
val webdir = "/Users/<your_absolute_path>/root"
  val homeHtml = "homeHtml"
  def route =
    concat(
      pathSingleSlash {
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, homeHtml)) // "hello world"
        }
      },
      (get & pathPrefix("test")) {
        (pathEndOrSingleSlash & redirectToTrailingSlashIfMissing(StatusCodes.TemporaryRedirect)) {
          getFromFile(s"$webdir/index.html")
        } ~ {
          getFromDirectory(webdir)
        }
      }
    )