How to select route based on header in Zuul
Asked Answered
A

1

6

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?

Angelitaangell answered 31/1, 2018 at 9:10 Comment(0)
G
6

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

Gallinacean answered 1/2, 2018 at 8:45 Comment(1)
As I did more research on this topic I found that the filter order should be less than 5 for the first option to work and greater than 5 for the second one. And 5 is the order of a built in filter called PreDecorationFilterAngelitaangell

© 2022 - 2024 — McMap. All rights reserved.