While playing with, akka-http experimental 1.0-M2 I am trying to create a simple Hello world example.
import akka.actor.ActorSystem
import akka.http.Http
import akka.http.model.HttpResponse
import akka.http.server.Route
import akka.stream.FlowMaterializer
import akka.http.server.Directives._
object Server extends App {
val host = "127.0.0.1"
val port = "8080"
implicit val system = ActorSystem("my-testing-system")
implicit val fm = FlowMaterializer()
val serverBinding = Http(system).bind(interface = host, port = port)
serverBinding.connections.foreach { connection ⇒
println("Accepted new connection from: " + connection.remoteAddress)
connection handleWith Route.handlerFlow {
path("") {
get {
complete(HttpResponse(entity = "Hello world?"))
}
}
}
}
}
Compilation fails with could not find implicit value for parameter setup: akka.http.server.RoutingSetup
Also, if I change
complete(HttpResponse(entity = "Hello world?"))
with
complete("Hello world?")
I get another error: type mismatch; found : String("Hello world?") required: akka.http.marshalling.ToResponseMarshallable
With research I was able to understand the issue to be lack of Execution Context
. To solve both the issue I needed to include this:
implicit val executionContext = system.dispatcher
Looking into akka/http/marshalling/ToResponseMarshallable.scala
I see ToResponseMarshallable.apply
requires it which returns a Future[HttpResponse]
.
Also, in akka/http/server/RoutingSetup.scala
, RoutingSetup.apply
needs it.
May be akka team just needs to add some more @implicitNotFound
s. I was able to find not exact but related answer at: direct use of Futures in Akka and spray Marshaller for futures not in implicit scope after upgrading to spray 1.2
Well found - this problem still exists with Akka HTTP 1.0-RC2, so the code for that now must look like this (given their API changes):
import akka.actor.ActorSystem
import akka.http.scaladsl.server._
import akka.http.scaladsl._
import akka.stream.ActorFlowMaterializer
import akka.stream.scaladsl.{Sink, Source}
import akka.http.scaladsl.model.HttpResponse
import Directives._
import scala.concurrent.Future
object BootWithRouting extends App {
val host = "127.0.0.1"
val port = 8080
implicit val system = ActorSystem("my-testing-system")
implicit val fm = ActorFlowMaterializer()
implicit val executionContext = system.dispatcher
val serverSource: Source[Http.IncomingConnection, Future[Http.ServerBinding]] =
Http(system).bind(interface = host, port = port)
serverSource.to(Sink.foreach {
connection =>
println("Accepted new connection from: " + connection.remoteAddress)
connection handleWith Route.handlerFlow {
path("") {
get {
complete(HttpResponse(entity = "Hello world?"))
}
}
}
}).run()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With