0

I have the following basic code to start an akk-http service and I would like to pass the client IP into my route handler.

...
final Flow<HttpRequest, HttpResponse, NotUsed> myFlow= myRoute().flow(actorSystem, actorMaterializer);

final CompletionStage<ServerBinding> binding = akkaHttp.bindAndHandle(myFlow,
ConnectHttp.toHost(configurationInstance.getBindAddress(), configurationInstance.getBindPort()), actorMaterializer);
...

I found this post:

Obtaining the client IP in Akka-http

However it uses the low level API.

So far I got this, but I do not want to change to the low level API. Is there a way to get this to work with the high level API? I get a compilation error on the myRoute(), I am not sure how I can create a handler for this approach.

    ...
            Http.get(system)
                    .bind(ConnectHttp.toHost(configurationInstance.getBindAddress(),
                        configurationInstance.getBindPort()), mat);

            CompletionStage<ServerBinding> binding =
                     rverSource.runWith(Sink.foreach(connection -> {
                             connection.handleWithAsyncHandler(   
                                myRoute(connection.remoteAddress()), mat); // ERROR   
                })).run(mat);
 ...
 public Route finalRoute(InetSocketAddress client) { .... }

-- (UPDATE) This is what worked, after the help from Stefano Bonetti, below.

ompletionStage<ServerBinding> binding =
          serverSource.to(Sink.foreach(connection -> {
                  connection.handleWith(MyRoute(connection.remoteAddress())
                  .flow(system, mat), mat);
                }
           )).run(mat);
Will I Am
  • 2,614
  • 3
  • 35
  • 61

1 Answers1

1

You should be able to convert you Route to a Flow[HttpRequest, HttpResponse, NotUsed] and pass it to the handleWith function.

connection.handleWith(myRoute(connection.remoteAddress()).flow(actorSystem, mat), mat);
Stefano Bonetti
  • 8,973
  • 1
  • 25
  • 44
  • I tried that, but I get: Error:(131, 30) java: method runWith in class akka.stream.javadsl.Source cannot be applied to given types; required: akka.stream.Graph,M>,akka.stream.Materializer found: akka.stream.javadsl.Sink> reason: cannot infer type-variable(s) M (actual and formal argument lists differ in length) – Will I Am Mar 01 '17 at 20:17
  • 1
    I did get it to work, your suggestion helped, but I had to make minor changes. I will update the original question with the code. – Will I Am Mar 01 '17 at 20:22