아래 문서를 근거로 요즘 뜨고 있다는 akka-http를 테스트해봤다.


http://doc.akka.io/docs/akka-http/10.0.2/scala/http/introduction.html


http://doc.akka.io/docs/akka-http/10.0.2/scala/http/routing-dsl/index.html#http-high-level-server-side-api



akka 10.0.2를 사용해서 저 수준 http api를 테스트해봤다.

[group: "com.typesafe.akka", name: "akka-http_$scalaMajor", version: "10.0.2"]
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import scala.io.StdIn
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model._

object WebServer extends App {

implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher

val requestHandler: HttpRequest => HttpResponse = {
case HttpRequest(GET, Uri.Path("/"), _, _, _) =>
HttpResponse(entity = HttpEntity(
ContentTypes.`text/html(UTF-8)`,
"<html><body>Hello world!</body></html>"))

case HttpRequest(GET, Uri.Path("/ping"), _, _, _) =>
HttpResponse(entity = "PONG!")

case HttpRequest(GET, Uri.Path("/crash"), _, _, _) =>
sys.error("Crash!")

case r: HttpRequest =>
r.discardEntityBytes() // important to drain incoming HTTP Entity stream
HttpResponse(404, entity = "Unknown resource!")
}

val bindingFuture = Http().bindAndHandleSync(requestHandler, "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

}







주의할 점은 여러 end point를 연결하기 위해 ~를 사용했다는 점이다. 



import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import scala.io.StdIn


object WebServer extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
// needed for the future flatMap/onComplete in the end
implicit val executionContext = system.dispatcher

val route =
get {
path("") {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<html><body>Hello world!</body></html>"))
} ~
path("ping") {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<html><body>PONG</body></html>"))
} ~
path("crash") {
sys.error("Crash!")
}
}

val bindingFuture = Http().bindAndHandle(route, "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

}





Posted by '김용환'
,