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)