feign icon indicating copy to clipboard operation
feign copied to clipboard

Pass RequestTemplate to the client implementation

Open cortex93 opened this issue 3 years ago • 0 comments

Feign allow to add request interceptor. Sometimes it is not sufficient and we need to use the low level client implementation extension mechanism but the requestTemplate context is not flowing and we miss some information.

For eg. I have apache httpclient request and response interceptor. They have access to the apache HttpContext and it should contains a way to get access to the requestTemplate.

I reimplement ApacheHttpClient and change the execute method to be

  @Override
  public Response execute(Request request, Request.Options options) throws IOException {
    HttpUriRequest httpUriRequest;
    try {
      httpUriRequest = toHttpUriRequest(request, options);
    } catch (URISyntaxException e) {
      throw new IOException("URL '" + request.url() + "' couldn't be parsed into a URI", e);
    }
    // inject requestTemplate to allow interceptors to know the feign request metadata
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute("feign.requestTemplate", request.requestTemplate());
    HttpResponse httpResponse = client.execute(httpUriRequest, context);
    return toFeignResponse(httpResponse, request);
  }

This is a simple modification but the actual ApacheHttpClient is final, meaning we need to copy/paste the whole class content.

The apache interceptor can then extract the requestTemplate and access any metadata it may needs like method annotations.

I don't know if this can be done for all client implementations, but a common pattern and a convention for the name of the key in the client context may be adopted.

cortex93 avatar Jun 12 '21 15:06 cortex93