akka-http: complete request with flow

拜拜、爱过 提交于 2019-11-29 09:52:42

问题


Assume I have set up an arbitrarily complex Flow[HttpRequest, HttpResponse, Unit].

I can already use said flow to handle incoming requests with

Http().bindAndHandle(flow, "0.0.0.0", 8080)

Now I would like to add logging, leveraging some existing directive, like logRequestResult("my-service"){...} Is there a way to combine this directive with my flow? I guess I am looking for another directive, something along the lines of

def completeWithFlow(flow: Flow): Route

Is this possible at all?

N.B.: logRequestResult is an example, my question applies to any Directive one might find useful.


回答1:


Turns out one (and maybe the only) way is to wire and materialize a new flow, and feed the extracted request to it. Example below

  val myFlow: Flow[HttpRequest, HttpResponse, NotUsed] = ???

  val route =
    get {
      logRequestResult("my-service") {
        extract(_.request) { req ⇒
          val futureResponse = Source.single(req).via(myFlow).runWith(Sink.head)
          complete(futureResponse)
        }
      }
    }

  Http().bindAndHandle(route, "127.0.0.1", 9000)



回答2:


http://doc.akka.io/docs/akka/2.4.2/scala/http/routing-dsl/overview.html

Are you looking for route2HandlerFlow or Route.handlerFlow ?

I believe Route.handlerFlow will work based on implicits.

eg /

val serverBinding = Http().bindAndHandle(interface = "0.0.0.0", port = 8080, 
handler = route2HandlerFlow(mainFlow()))


来源:https://stackoverflow.com/questions/36294428/akka-http-complete-request-with-flow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!