forked from geekr-dev/openai-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (78 loc) · 2.32 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"crypto/tls"
"io"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
)
var (
target = "https://api.openai.com" // 目标域名
httpProxy = "http://127.0.0.1:10809" // 本地代理地址和端口
)
func main() {
http.HandleFunc("/", handleRequest)
http.ListenAndServe(":9000", nil)
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
// 过滤无效URL
_, err := url.Parse(r.URL.String())
if err != nil {
log.Println("Error parsing URL: ", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
// 去掉环境前缀(针对腾讯云,如果包含的话,目前我只用到了test和release)
newPath := strings.Replace(r.URL.Path, "/release", "", 1)
newPath = strings.Replace(newPath, "/test", "", 1)
// 拼接目标URL
targetURL := target + newPath
// 创建代理HTTP请求
proxyReq, err := http.NewRequest(r.Method, targetURL, r.Body)
if err != nil {
log.Println("Error creating proxy request: ", err.Error())
http.Error(w, "Error creating proxy request", http.StatusInternalServerError)
return
}
// 将原始请求头复制到新请求中
for headerKey, headerValues := range r.Header {
for _, headerValue := range headerValues {
if strings.ToLower(headerKey) != strings.ToLower("host"){
proxyReq.Header.Add(headerKey, headerValue)
}
}
}
// 默认超时时间设置为60s
client := &http.Client{
Timeout: 60 * time.Second,
}
// 本地测试通过代理请求 OpenAI 接口
if os.Getenv("ENV") == "local" {
proxyURL, _ := url.Parse(httpProxy) // 本地HTTP代理配置
client.Transport = &http.Transport{
Proxy: http.ProxyURL(proxyURL),
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
// 向 OpenAI 发起代理请求
resp, err := client.Do(proxyReq)
if err != nil {
log.Println("Error sending proxy request: ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
// 将响应头复制到代理响应头中
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
// 将响应状态码设置为原始响应状态码
w.WriteHeader(resp.StatusCode)
// 将响应实体写入到响应流中(支持流式响应)
io.Copy(w, resp.Body)
}