import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
 
import java.net.URI;
 
@Component
public class ModifyRequestGlobalFilter implements GlobalFilter, Ordered {
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取原始请求
        ServerHttpRequest request = exchange.getRequest();
 
        // 修改请求路径,例如添加一个路径片段
        String modifiedPath = request.getPath().pathWithinApplication()
                                     .value() + "/modified";
 
        // 构建新的请求
        ServerHttpRequest newRequest = request.mutate()
                                             .path(modifiedPath)
                                             .build();
 
        // 返回修改后的请求
        return chain.filter(exchange.mutate().request(newRequest).build());
    }
 
    @Override
    public int getOrder() {
        // 确保此全局过滤器在其他过滤器之前运行
        return -1;
    }
}

https://github.com/spring-cloud/spring-cloud-gateway/issues/59

public class HeaderFilterFactory implements WebFilterFactory {
    @Override
    public WebFilter apply(Tuple args) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest().mutate().build();
            request.getHeaders().add("Connection", "Upgrade");
            request.getHeaders().add("Upgrade", "websocket");
            request.getHeaders().add("Sec-WebSocket-Protocol", "base64.channel.k8s.io");
            return chain.filter(exchange.mutate().request(request).build());
        };
    }
}