0

I have implemented a zuul gateway service for the communication between some micro services that i have wrote. I have a specific scenario like i want to change the service path in one of my custom filter and redirected to some other service. Is this possible with the zuul gateway?. I have tried putting "requestURI" parameter with the updated uri to the request context in my route filter but that didn't worked out well

Please help me out guys thanks in advance

Arunkumar
  • 1
  • 3

1 Answers1

0

yes, you can. for that you need to implement ZuulFilter with type PRE_TYPE, and update response with specified Location header and response status either 301 or 302.

@Slf4j
public class CustomRedirectFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_FORWARD_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String requestUrl = ctx.getRequest().getRequestURL().toString();

        if (shouldBeRedirected(requestUrl)) {
            String redirectUrl = generateRedirectUrl(ctx.getRequest());
            sendRedirect(ctx.getResponse(), redirectUrl);
        }
        return null;
    }

    private void sendRedirect(HttpServletResponse response, String redirectUrl){
        try {
            response.setHeader(HttpHeaders.LOCATION, redirectUrl);
            response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());
            response.flushBuffer();
        } catch (IOException ex) {
            log.error("Could not redirect to: " + redirectUrl, ex);
        }
    }

    private boolean shouldBeRedirected(String requestUrl) {
        // your logic whether should we redirect request or not
        return true;
    }

    private String generateRedirectUrl(HttpServletRequest request) {
        String queryParams = request.getQueryString();
        String currentUrl =  request.getRequestURL().toString() + (queryParams == null ? "" : ("?" + queryParams));
        // update url
        return updatedUrl;
    }
}
Vasyl Sarzhynskyi
  • 3,689
  • 2
  • 22
  • 55
  • but my request is a POST one. can i redirect a post request in the same way? – Arunkumar Jul 29 '18 at 15:55
  • I am getting the url like **/abc/{id}/def/v1/add** in the gateway , I need to route that url to **/def/v1/add** . this is my requirement .@Vasiliy Sarzhynskyi – Arunkumar Jul 29 '18 at 16:24