Warm tip: This article is reproduced from serverfault.com, please click

Akka HTTP Routing DSL example is invalid

发布于 2020-11-29 14:51:33

So I'm trying to build a minimal HTTP server to receive POST requests but I can't get it done because somehow the examples on the Akka docs are invalid and I can't get the executionContext from anywhere.

Here is my code:

object Main extends App {

  implicit val system: ActorSystem = ActorSystem("server-system")
  implicit val executionContext = system.executionContext  // can't resolve symbol executionContext

  // test route
  val route =
    path("test") {
      get {
        complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`, "test"))
      }
    }

  val address = "localhost"
  val port = 8080
  val bindingFuture = Http().newServerAt(address, port).bind(route)
  println(s"Server online at $address:$port\nPress RETURN to stop...")

  StdIn.readLine()
  bindingFuture
    .flatMap(_.unbind())                  // no implicits found for parameter
    .onComplete(_ => system.terminate())  // executor: ExecutorContext

}

I'm using version 10.2.1 which I'm importing with gradle like this:

compile group: 'com.typesafe.akka', name: "akka-http_2.12", version: "10.2.1"
compile group: 'com.typesafe.akka', name: "akka-stream_2.12", version: "2.6.8"

Do you have any other quickstart example valid, or any other library which could be easier to use in order to setup a very minimal server like I'm trying to?

Questioner
NoeXWolf
Viewed
0
Tomer Shetah 2020-11-29 23:28:17

There are many ways to define ExecutionContext in Scala. 2 of them for example are:

implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.global

or:

implicit val ec: ExecutionContext = system.dispatcher

But before choosing which one you actually want to use, I suggest reading What is execution context in Scala?

You can also read Dispatchers by Akka for more customisable options. There is also the post Execution Context and Dispatcher - Best practices, useful configurations and Documentation.