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.

Stefano Bonetti
  • 8,973
  • 1
  • 25
  • 44
  • Why does logging have to be provided by a Directive? Why can't you just use Flow.log? – Ramón J Romero y Vigil Mar 31 '16 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. – Stefano Bonetti Mar 31 '16 at 14:48

2 Answers2

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)
Stefano Bonetti
  • 8,973
  • 1
  • 25
  • 44
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()))
tacos_tacos_tacos
  • 10,277
  • 11
  • 73
  • 126