6

I want to use akka-http like http server (for example tomcat or nginx server) .
with this simple code can load html sources from web browsers but can not load other source linked on html file .

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer

import scala.io.StdIn

object MainRunner extends App {

  implicit val system = ActorSystem("mySystem")
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher

  val staticResources =
    get {
        path("admin") {
          getFromResource("admin/index.html")
        } ~ pathPrefix("admin") {
        getFromResourceDirectory("admin")
      }
    }

  val bindingFuture = Http().bindAndHandle(staticResources, "localhost", 8080)

  println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
  StdIn.readLine() // let it run until user presses return
  bindingFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ => system.terminate()) // and shutdown when done
}

this is my html file :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
<h1>Admin area</h1>
</body>
</html>

and receive this error in browser : enter image description here This is directory structure :
enter image description here

How can fix this problem ?

Stefano Bonetti
  • 8,973
  • 1
  • 25
  • 44
mah454
  • 1,571
  • 15
  • 38

2 Answers2

10

You will need your route to add trailing slash when hitting the static resources paths. The redirectToTrailingSlashIfMissing directive should do the trick:

import akka.http.scaladsl.model.StatusCodes

val staticResources =
  (get & pathPrefix("admin")){
    (pathEndOrSingleSlash & redirectToTrailingSlashIfMissing(StatusCodes.TemporaryRedirect)) {
      getFromResource("admin/index.html")
    } ~ {
      getFromResourceDirectory("admin")
    }
  }
Dexter Legaspi
  • 3,192
  • 1
  • 35
  • 26
Stefano Bonetti
  • 8,973
  • 1
  • 25
  • 44
1

You need following directive

get {
  getFromResourceDirectory("admin")
}
expert
  • 29,290
  • 30
  • 110
  • 214
  • this won't work the way OP wants it to work; `index.html` will only load if user explicitly goes to url `admin/index.html` but not for `admin` or `admin/` – Dexter Legaspi Aug 25 '18 at 14:17