zhentao 2 weeks ago
parent
commit
bcf184c583

+ 42 - 0
src/main/java/com/zhentao/information/config/WebSocketHandshakeInterceptor.java

@@ -0,0 +1,42 @@
+package com.zhentao.information.config;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.util.AttributeKey;
+import java.net.URI;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+
+public class WebSocketHandshakeInterceptor extends ChannelInboundHandlerAdapter {
+    public static final AttributeKey<String> PEER_ID_KEY = AttributeKey.valueOf("peerId");
+    public static final AttributeKey<String> TOKEN_KEY = AttributeKey.valueOf("token");
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+        if (msg instanceof FullHttpRequest) {
+            FullHttpRequest req = (FullHttpRequest) msg;
+            URI uri = new URI(req.uri());
+            String query = uri.getQuery();
+            if (query != null) {
+                Map<String, String> params = new HashMap<>();
+                for (String param : query.split("&")) {
+                    String[] pair = param.split("=");
+                    if (pair.length == 2) {
+                        params.put(URLDecoder.decode(pair[0], String.valueOf(StandardCharsets.UTF_8)),
+                                   URLDecoder.decode(pair[1], String.valueOf(StandardCharsets.UTF_8)));
+                    }
+                }
+                if (params.containsKey("peerId")) {
+                    ctx.channel().attr(PEER_ID_KEY).set(params.get("peerId"));
+                }
+                if (params.containsKey("token")) {
+                    ctx.channel().attr(TOKEN_KEY).set(params.get("token"));
+                }
+            }
+        }
+        super.channelRead(ctx, msg);
+    }
+}