Spring Config for RestTemplate to use contextPath from Consul
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Workaround to let RestTemplate use the contextPath from Consul when calling URLs | |
* (instead of only using the host and port) | |
* See https://github.com/spring-cloud/spring-cloud-consul/issues/376 | |
* | |
* Put this in any spring config class | |
*/ | |
@Bean | |
LoadBalancerRequestTransformer consulContextPathTransformer() { | |
new LoadBalancerRequestTransformer() { | |
@Override | |
HttpRequest transformRequest(HttpRequest request, ServiceInstance instance) { | |
String contextPath = instance?.server?.metadata?.contextPath | |
contextPath ? new ConsulContextPathServiceRequestWrapper(request, contextPath) : request | |
} | |
} | |
} | |
class ConsulContextPathServiceRequestWrapper extends ServiceRequestWrapper { | |
final String contextPath | |
ConsulContextPathServiceRequestWrapper(ServiceRequestWrapper serviceRequestWrapper, String contextPath) { | |
super(serviceRequestWrapper.request, serviceRequestWrapper.instance, serviceRequestWrapper.loadBalancer) | |
this.contextPath = contextPath | |
} | |
@Override | |
URI getURI() { | |
URI origURI = super.getURI() | |
new URIBuilder(origURI).setPath(contextPath + origURI.path).build() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment