Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka-Http load css&js resources

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 ?

like image 813
mah454 Avatar asked Dec 16 '16 07:12

mah454


2 Answers

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")
    }
  }
like image 106
Stefano Bonetti Avatar answered Nov 08 '22 12:11

Stefano Bonetti


You need following directive

get {
  getFromResourceDirectory("admin")
}
like image 1
expert Avatar answered Nov 08 '22 14:11

expert