Skip to content

Commit 6f29fbb

Browse files
committed
支持通过x-target-host请求头设置任意代理域名
1 parent 855539d commit 6f29fbb

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

main.go

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
package main
22

33
import (
4-
"crypto/tls"
54
"flag"
5+
"fmt"
66
"io"
77
"log"
88
"net/http"
99
"net/url"
1010
"os"
1111
"strconv"
1212
"strings"
13-
"time"
1413
)
1514

1615
var (
17-
target string // 目标域名
18-
port int // 代理端口
19-
httpProxy = "http://127.0.0.1:10809" // 本地代理地址和端口
16+
target string // 目标域名
17+
port int // 代理端口
18+
// httpProxy = "http://127.0.0.1:10809" // 本地代理地址和端口
2019
)
2120

2221
func main() {
@@ -42,6 +41,12 @@ func handleRequest(w http.ResponseWriter, r *http.Request) {
4241
return
4342
}
4443

44+
// 如果请求中包含 X-Target-Host 头,则使用该头作为目标域名
45+
// 优先级 header > args > default
46+
if r.Header.Get("X-Target-Host") != "" {
47+
target = "https://" + r.Header.Get("X-Target-Host")
48+
}
49+
4550
// 去掉环境前缀(针对腾讯云,如果包含的话,目前我只用到了test和release)
4651
newPath := strings.Replace(r.URL.Path, "/release", "", 1)
4752
newPath = strings.Replace(newPath, "/test", "", 1)
@@ -52,6 +57,11 @@ func handleRequest(w http.ResponseWriter, r *http.Request) {
5257
targetURL += "?" + r.URL.RawQuery
5358
}
5459

60+
// 本地打印代理请求完整URL用于调试
61+
if os.Getenv("ENV") == "local" {
62+
fmt.Printf("Proxying request to: %s\n", targetURL)
63+
}
64+
5565
// 创建代理HTTP请求
5666
proxyReq, err := http.NewRequest(r.Method, targetURL, r.Body)
5767
if err != nil {
@@ -69,19 +79,19 @@ func handleRequest(w http.ResponseWriter, r *http.Request) {
6979

7080
// 默认超时时间设置为300s(应对长上下文)
7181
client := &http.Client{
72-
Timeout: 300 * time.Second,
82+
// Timeout: 300 * time.Second, // 代理不干涉超时逻辑,由客户端自行设置
7383
}
7484

75-
// 本地测试通过代理请求 OpenAI 接口
76-
if os.Getenv("ENV") == "local" {
85+
// 支持本地测试通过代理请求
86+
/*if os.Getenv("ENV") == "local" {
7787
proxyURL, _ := url.Parse(httpProxy) // 本地HTTP代理配置
7888
client.Transport = &http.Transport{
7989
Proxy: http.ProxyURL(proxyURL),
8090
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
8191
}
82-
}
92+
}*/
8393

84-
// 向 OpenAI 发起代理请求
94+
// 发起代理请求
8595
resp, err := client.Do(proxyReq)
8696
if err != nil {
8797
log.Println("Error sending proxy request: ", err.Error())

0 commit comments

Comments
 (0)