暗中观察

Spring Cloud Gateway 忽略网关特殊字符
import io.netty.channel.ChannelHandlerContext; import io....
扫描右侧二维码阅读全文
25
2023/09

Spring Cloud Gateway 忽略网关特殊字符

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
import reactor.netty.ConnectionObserver;
import reactor.netty.NettyPipeline;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class EncodeQueryNettyWebServerCustomizer implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {

    /**
     * 需要encode的特殊字符
     */
    private final List<Character> charList = new ArrayList<Character>() {
        {
//            this.add('{');
//            this.add('}');
//            this.add('[');
//            this.add(']');
            this.add('|');
        }
    };

    @Override
    public void customize(NettyReactiveWebServerFactory factory) {
        factory.addServerCustomizers(httpServer -> httpServer.observe((conn, state) -> {
            if (state == ConnectionObserver.State.CONNECTED) {
                conn.channel().pipeline().addAfter(NettyPipeline.HttpCodec, "", new QueryHandler());
            }
        }));
    }

    class QueryHandler extends ChannelInboundHandlerAdapter {

        QueryHandler() {
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
            if (msg instanceof HttpRequest) {
                HttpRequest request = (HttpRequest) msg;
                String url = request.uri();
                // fix url
                log.info("url: {}", url);
                String[] split = url.split("\\?");
                StringBuilder fixUrl = new StringBuilder(split[0]);
                if (split.length > 1) {
                    fixUrl.append("?");
                    char[] chars = split[1].toCharArray();
                    for (char aChar : chars) {
                        if (charList.contains(aChar)) {
                            fixUrl.append(URLEncoder.encode(String.valueOf(aChar), "UTF-8"));
                        } else {
                            fixUrl.append(aChar);
                        }
                    }
                }
                log.info("fixUrl: {}", fixUrl);
                request.setUri(fixUrl.toString());
            }
            ctx.fireChannelRead(msg);
        }
    }
}
Last modification:October 31st, 2023 at 01:59 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment