10

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.

2
  • Why does logging have to be provided by a Directive? Why can't you just use Flow.log? Mar 31, 2016 at 13:40
  • Yes, I could use Flow.log for that specific example. my question was a bit more generic, as in: if I have a ready-to-use directive I would like to leverage, how can I reuse it in my context? Let's say I want to handle .favicon requests leveraging the directives below path("favicon.ico") { getFromResource("favicon.ico", image/x-icon) } I would like to be able to use this directive in combination with my flow, e.g. use my flow to serve a specific path, and use the directive above to serve /favicon. Mar 31, 2016 at 14:48

2 Answers 2

7

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)
1
  • is this still the status in 2019?
    – shay__
    Apr 21, 2019 at 16:26
0

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()))
2
  • Thank you, I am in fact looking for the opposite. Apr 4, 2016 at 20:06
  • 2
    :) Always glad to be of help... to someone... maybe Apr 4, 2016 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.