Search code examples
netflix-zuulspring-cloud-netflix

How to select route based on header in Zuul


I'm using a Netflix Zuul proxy in front of my services A and B.

How can I make the Zuul proxy to choose between routes to A and B based on a HTTP header in the incoming request?


Solution

  • You should create a prefilter based on your logic. Something like this :

    @Component
    public class RedirectionFilter extends ZuulFilter {
    
    @Override
    public String filterType() {
       return "pre";
    }
    
    @Override
    public int filterOrder() {
       return 2;
    }
    
    @Override
    public boolean shouldFilter() {
      return true;
    }
    
    @Override
    public Object run() {
      RequestContext ctx = RequestContext.getCurrentContext();
      HttpServletRequest request = ctx.getRequest();`
      String header = request.getHeader("YOUR_HEADER_PARAM");
    
      if ("YOUR_A_LOGIC".equals(header) ) {
        ctx.put("serviceId", "serviceA");
        //ctx.setRouteHost(new URL("http://Service_A_URL”));
      } else { // "YOUR_B_LOGIC"
        ctx.put("serviceId", "serviceB");
        //ctx.setRouteHost(new URL("http://Service_B_URL”));
      }
      log.info(String.format("%s request to %s", request.getMethod(), 
      request.getRequestURL().toString()));
      return null;
     }
    

    Im not sure 100% about the redirection part, but it's a beginning for your needs. i added second option for redirection (commented lines), maybe one of the 2 options will help you.

    Also see this example