2014-09-11 17:15:26 +02:00
|
|
|
/*
|
|
|
|
|
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
|
|
|
|
|
*/
|
|
|
|
|
|
2014-09-17 16:42:31 +02:00
|
|
|
package akka.http.server
|
2014-09-11 17:15:26 +02:00
|
|
|
|
2014-11-03 16:27:38 +01:00
|
|
|
import akka.http.marshalling.Marshaller
|
|
|
|
|
import akka.http.server.directives.AuthenticationDirectives._
|
2014-09-11 17:15:26 +02:00
|
|
|
import com.typesafe.config.{ ConfigFactory, Config }
|
|
|
|
|
import scala.concurrent.duration._
|
|
|
|
|
import akka.actor.ActorSystem
|
|
|
|
|
import akka.io.IO
|
2014-10-27 14:35:41 +01:00
|
|
|
import akka.stream.FlowMaterializer
|
2014-09-11 17:15:26 +02:00
|
|
|
import akka.util.Timeout
|
|
|
|
|
import akka.pattern.ask
|
|
|
|
|
import akka.http.Http
|
|
|
|
|
import akka.http.model._
|
|
|
|
|
|
|
|
|
|
object TestServer extends App {
|
|
|
|
|
val testConf: Config = ConfigFactory.parseString("""
|
|
|
|
|
akka.loglevel = INFO
|
|
|
|
|
akka.log-dead-letters = off
|
|
|
|
|
""")
|
|
|
|
|
implicit val system = ActorSystem("ServerTest", testConf)
|
|
|
|
|
import system.dispatcher
|
|
|
|
|
implicit val materializer = FlowMaterializer()
|
|
|
|
|
|
|
|
|
|
implicit val askTimeout: Timeout = 500.millis
|
|
|
|
|
val bindingFuture = (IO(Http) ? Http.Bind(interface = "localhost", port = 8080)).mapTo[Http.ServerBinding]
|
|
|
|
|
|
|
|
|
|
import ScalaRoutingDSL._
|
|
|
|
|
|
2014-11-03 16:27:38 +01:00
|
|
|
def auth =
|
|
|
|
|
HttpBasicAuthenticator.provideUserName {
|
|
|
|
|
case p @ UserCredentials.Provided(name) ⇒ p.verifySecret(name + "-password")
|
|
|
|
|
case _ ⇒ false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
implicit val html = Marshaller.nodeSeqMarshaller(MediaTypes.`text/html`)
|
|
|
|
|
|
2014-09-11 17:15:26 +02:00
|
|
|
handleConnections(bindingFuture) withRoute {
|
|
|
|
|
get {
|
|
|
|
|
path("") {
|
|
|
|
|
complete(index)
|
|
|
|
|
} ~
|
2014-11-03 16:27:38 +01:00
|
|
|
path("secure") {
|
|
|
|
|
HttpBasicAuthentication("My very secure site")(auth) { user ⇒
|
|
|
|
|
complete(<html><body>Hello <b>{ user }</b>. Access has been granted!</body></html>)
|
|
|
|
|
}
|
|
|
|
|
} ~
|
2014-09-11 17:15:26 +02:00
|
|
|
path("ping") {
|
|
|
|
|
complete("PONG!")
|
|
|
|
|
} ~
|
|
|
|
|
path("crash") {
|
|
|
|
|
complete(sys.error("BOOM!"))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
|
|
|
|
|
|
|
|
|
|
Console.readLine()
|
|
|
|
|
system.shutdown()
|
|
|
|
|
|
2014-11-03 16:27:38 +01:00
|
|
|
lazy val index =
|
|
|
|
|
<html>
|
|
|
|
|
<body>
|
|
|
|
|
<h1>Say hello to <i>akka-http-core</i>!</h1>
|
|
|
|
|
<p>Defined resources:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><a href="/ping">/ping</a></li>
|
|
|
|
|
<li><a href="/secure">/secure</a> Use any username and '<username>-password' as credentials</li>
|
|
|
|
|
<li><a href="/crash">/crash</a></li>
|
|
|
|
|
</ul>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|
2014-09-11 17:15:26 +02:00
|
|
|
}
|