Will I Am Will I Am -4 years ago 215
Java Question

Akka-http, getting client IP in Java

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.

configurationInstance.getBindPort()), mat);

CompletionStage<ServerBinding> binding =
rverSource.runWith(Sink.foreach(connection -> {
myRoute(connection.remoteAddress()), mat); // ERROR
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 -> {
.flow(system, mat), mat);

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download