package ink.wgink.gateway.filter.local;

import ink.wgink.gateway.consts.ISystemConst;
import ink.wgink.gateway.pojo.route.Route;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.filter.factory.RewritePathGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.SetPathGatewayFilterFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: CommonFilters
 * @Description: 通用过滤器
 * @Author: WangGeng
 * @Date: 2021/4/24 20:31
 * @Version: 1.0
 **/
public class CommonFilters {

    /**
     * 重写过滤器
     *
     * @param route
     * @return
     */
    public FilterDefinition rewriteFilterDefinition(Route route) {
        FilterDefinition rewritePathFilterDefinition = new FilterDefinition();
        Map<String, String> rewritePathFilterDefinitionMap = new HashMap<>(4);
        rewritePathFilterDefinitionMap.put(RewritePathGatewayFilterFactory.REGEXP_KEY, ISystemConst.ROUTE_PREFIX + "/?(?<segment>.*)");
        rewritePathFilterDefinitionMap.put(RewritePathGatewayFilterFactory.REPLACEMENT_KEY, "/$\\{segment}");
        rewritePathFilterDefinition.setArgs(rewritePathFilterDefinitionMap);
        rewritePathFilterDefinition.setName("RewritePath");
        return rewritePathFilterDefinition;
    }

    /**
     * 设置路径过滤器，去除前缀
     *
     * @param route
     * @return
     */
    public FilterDefinition setPathFilterDefinition(Route route) {
        FilterDefinition setPathFilterDefinition = new FilterDefinition();
        Map<String, String> setPathFilterDefinitionMap = new HashMap<>(2);
        setPathFilterDefinitionMap.put(SetPathGatewayFilterFactory.TEMPLATE_KEY, route.getPath().replaceFirst(ISystemConst.ROUTE_PREFIX, "/"));
        setPathFilterDefinition.setArgs(setPathFilterDefinitionMap);
        setPathFilterDefinition.setName("SetPath");
        return setPathFilterDefinition;
    }

}
