From 737fd041a0ebdd27a14d185a185da8653e80feb7 Mon Sep 17 00:00:00 2001 From: black1552 Date: Fri, 6 Mar 2026 11:14:10 +0800 Subject: [PATCH] =?UTF-8?q?feat(gateway):=20=E6=B7=BB=E5=8A=A0=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=E8=87=AA=E5=8A=A8=E6=A3=80=E6=B5=8B=E5=92=8C=E8=A1=A5?= =?UTF-8?q?=E5=85=A8=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现 hasProtocol 函数检查字符串是否包含协议前缀 - 支持 http、https、ws、wss 协议检测 - 自动为没有协议的主机地址添加相应协议前缀 - 根据请求类型判断协议:WebSocket 使用 ws,HTTP 使用 http - 优化反向代理请求构建逻辑 --- server/gateway.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/server/gateway.go b/server/gateway.go index 5ce4187..6c9917b 100644 --- a/server/gateway.go +++ b/server/gateway.go @@ -4,16 +4,36 @@ import ( "net/http" "net/http/httputil" "net/url" + "strings" "git.magicany.cc/black1552/gf-common/log" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/os/gctx" ) +// hasProtocol 检查字符串是否包含协议前缀 +func hasProtocol(s string) bool { + return strings.HasPrefix(s, "http://") || + strings.HasPrefix(s, "https://") || + strings.HasPrefix(s, "ws://") || + strings.HasPrefix(s, "wss://") +} + // BuildRequest 反向代理请求到指定主机 // 自动支持所有 HTTP 方法及 WebSocket 连接 func BuildRequest(r *ghttp.Request, host string) { - targetURL, err := url.Parse(host) + // 自动添加协议前缀 + targetHost := host + if !hasProtocol(host) { + // 根据请求判断协议:WebSocket 用 ws,普通 HTTP 用 http + if r.Header.Get("Upgrade") == "websocket" { + targetHost = "ws://" + host + } else { + targetHost = "http://" + host + } + } + + targetURL, err := url.Parse(targetHost) if err != nil { log.Error(gctx.New(), "parse target host error:", err) r.Response.WriteStatus(http.StatusInternalServerError)