Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spring Config for RestTemplate to use contextPath from Consul
/**
* 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
You can’t perform that action at this time.