ZUUL modify request query param

对于url路由的服务来说,可以修改context的queryParam来达到修改请求参数的目的。

package com.efivestar.springcloud.gateway.filters.demo;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.List;
import java.util.Map;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;

/**
 * @author Spencer Gibb
 */
public class QueryParamUpdatePreFilter extends ZuulFilter {
    private final Logger log = LoggerFactory.getLogger(getClass());

    public int filterOrder() {
        // run before PreDecorationFilter
        return 5 - 1;
    }

    public String filterType() {
        return "pre";
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = getCurrentContext();
        return context.getRequest().getRequestURI().startsWith("/test/");
    }

    public Object run() {
        RequestContext ctx = getCurrentContext();
        final Map<String, List<String>> requestQueryParams = ctx.getRequestQueryParams();
        if(requestQueryParams.containsKey("access_token")) {
            requestQueryParams.put("accesstoken", requestQueryParams.get("access_token"));
            requestQueryParams.remove("access_token");
            ctx.setRequestQueryParams(requestQueryParams);
        }
        return null;
    }
}

参考资料

Leave a Comment

电子邮件地址不会被公开。 必填项已用*标注