Created
August 12, 2016 09:06
-
-
Save kakawait/e1b5c67a9a262a684c5d0f3c2b61ae4d to your computer and use it in GitHub Desktop.
LoadBalancedUrlFilter
This file contains hidden or 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
import com.netflix.zuul.ZuulFilter; | |
import com.netflix.zuul.context.RequestContext; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; | |
import org.springframework.stereotype.Component; | |
import org.springframework.util.StringUtils; | |
import javax.servlet.http.HttpServletRequest; | |
import java.net.URL; | |
/** | |
* @author Thibaud Leprêtre | |
*/ | |
@Component | |
public class LoadBalancedUrlFilter extends ZuulFilter { | |
private final ZuulProperties properties; | |
@Autowired | |
public LoadBalancedUrlFilter(ZuulProperties properties) { | |
this.properties = properties; | |
} | |
@Override | |
public String filterType() { | |
return "pre"; | |
} | |
@Override | |
public int filterOrder() { | |
return 10; | |
} | |
@Override | |
public boolean shouldFilter() { | |
RequestContext ctx = RequestContext.getCurrentContext(); | |
return !ctx.containsKey("serviceId") && ctx.getRouteHost() != null; | |
} | |
@Override | |
public Object run() { | |
RequestContext ctx = RequestContext.getCurrentContext(); | |
URL url = ctx.getRouteHost(); | |
String serviceId = url.getHost(); | |
ctx.set("serviceId", serviceId); | |
ctx.setRouteHost(null); | |
ctx.addOriginResponseHeader("X-Zuul-ServiceId", serviceId); | |
String path = !ctx.containsKey("requestURI") ? "" : (String) ctx.get("requestURI"); | |
ctx.set("requestURI", (url.getPath() + path).replace("//", "/")); | |
if (properties.isAddProxyHeaders()) { | |
HttpServletRequest request = ctx.getRequest(); | |
String prefix = (request.getHeader("X-Forwarded-Prefix") == null) | |
? "" : request.getHeader("X-Forwarded-Prefix"); | |
String newPrefix = url.getPath() + prefix; | |
if (StringUtils.hasText(newPrefix) && !newPrefix.equals("/")) { | |
ctx.addZuulRequestHeader("X-Forwarded-Prefix", newPrefix.replace("//", "/")); | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment