feat(gateway): 添加协议自动检测和补全功能

- 实现 hasProtocol 函数检查字符串是否包含协议前缀
- 支持 http、https、ws、wss 协议检测
- 自动为没有协议的主机地址添加相应协议前缀
- 根据请求类型判断协议:WebSocket 使用 ws,HTTP 使用 http
- 优化反向代理请求构建逻辑
main v1.0.1014
black1552 2026-03-06 11:14:10 +08:00
parent 969322a912
commit 737fd041a0
1 changed files with 21 additions and 1 deletions

View File

@ -4,16 +4,36 @@ import (
"net/http" "net/http"
"net/http/httputil" "net/http/httputil"
"net/url" "net/url"
"strings"
"git.magicany.cc/black1552/gf-common/log" "git.magicany.cc/black1552/gf-common/log"
"github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gctx" "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 反向代理请求到指定主机 // BuildRequest 反向代理请求到指定主机
// 自动支持所有 HTTP 方法及 WebSocket 连接 // 自动支持所有 HTTP 方法及 WebSocket 连接
func BuildRequest(r *ghttp.Request, host string) { 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 { if err != nil {
log.Error(gctx.New(), "parse target host error:", err) log.Error(gctx.New(), "parse target host error:", err)
r.Response.WriteStatus(http.StatusInternalServerError) r.Response.WriteStatus(http.StatusInternalServerError)