Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffsheets/53a007401ab81f8cab4e9e3c5fa29cc0 to your computer and use it in GitHub Desktop.
Save jeffsheets/53a007401ab81f8cab4e9e3c5fa29cc0 to your computer and use it in GitHub Desktop.
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