Treat index.html as default file in Akka HTTP's getFromDirectory

元气小坏坏 提交于 2021-02-09 06:59:29

问题


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)
}

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/.

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")
  }

But:

  • This only makes http://localhost:8080/foo work, not http://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.

回答1:


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")
  }

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)
  }

This can then be called with

val barRoute = routeAsDir("foo" / "bar", "foo/bar")

Functional Akka Http

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...



来源:https://stackoverflow.com/questions/42871098/treat-index-html-as-default-file-in-akka-https-getfromdirectory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!