micronautmicronaut-client

micronaut redirect httprequest to different service


In micronaut there are declarative clients:

@Client("http://localhost:5000")
public interface ServiceB {

    @Get("/ping")
    HttpResponse ping(HttpRequest httpRequest);
}

In my controller class I want to redirect the incoming request to ServiceB

@Controller("/api")
public class ServiceA {

    @Inject
    private ServiceB serviceB;

    @Get("/ping)
    HttpResponse pingOtherService(HttpRequest httpRequest){
        return serviceB.ping(httpRequest)
    }

}

However it seems that ServiceB will never get the request because of the information encoded in the request. How can I forward the request from ServiceA to ServiceB ?


Solution

  • The client can't send and HttpRequest directly. He will build one from the parameters of the client.

    I tried to send the request to redirect in the body of the client, but get a stack overflow error : jackson can't convert it to string.

    You can't change the URI in the request to send it back unfortunatly, no HttpRequest implementation have a setter on the URI.

    If you really want to send the full request (header, body, params...) you can try to configure a proxy.

    Else, if you don't have to pass the full request, you can pass through the client what you need :

    Client example:

    @Client("http://localhost:8080/test")
    public interface RedirectClient {
    
      @Get("/redirect")
      String redirect(@Header(value = "test") String header);
    
    }
    

    The controller :

    @Slf4j
    @Controller("/test")
    public class RedirectController {
    
      @Inject
      private RedirectClient client;
    
      @Get
      public String redirect(HttpRequest request){
        log.info("headers : {}", request.getHeaders().findFirst("test"));
        return client.redirect(request.getHeaders().get("test"));
      }
    
      @Get("/redirect")
      public String hello(HttpRequest request){
        log.info("headers : {}", request.getHeaders().findFirst("test"));
        return "Hello from redirect";
      }
    }
    

    I did it for one header, but you can do it with a body (if not a GET method), for request params, and so on.