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 :
This is directory structure :
How can fix this problem ?
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")
}
}
You need following directive
get {
getFromResourceDirectory("admin")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With