아래 문서를 근거로 요즘 뜨고 있다는 akka-http를 테스트해봤다.
http://doc.akka.io/docs/akka-http/10.0.2/scala/http/introduction.html
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
}
'scala' 카테고리의 다른 글
[play] The application secret has not been set, and we are in prod mode. Your application is not secure. 해결하기 (0) | 2017.04.17 |
---|---|
[sbt] sbt 동작을 로그로 확인하기 (0) | 2017.04.17 |
[akka] 처음 시작하는 Actor 공부-액터 모델/액터 레퍼런스/라이프 사이클/중지/종료 (0) | 2017.04.09 |
[brew] 맥 OS에서 scala 업그레이드 (0) | 2017.04.07 |
[scala] case object와 object의 차이, (0) | 2017.04.03 |