-
Notifications
You must be signed in to change notification settings - Fork 1
/
google_ai_proxy.go
63 lines (55 loc) · 1.38 KB
/
google_ai_proxy.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
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
)
func main() {
// 下面的URL应该被替换成你需要转发到的服务的URL
targetServiceURL := "https://generativelanguage.googleapis.com"
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// 创建一个新的请求
targetUrl := targetServiceURL + r.URL.Path
baseUrl, err := url.Parse(targetUrl)
if err != nil {
panic(err)
}
// 创建并设置查询参数
params := url.Values{}
for k, v := range r.URL.Query() {
params.Add(k, v[0])
}
baseUrl.RawQuery = params.Encode()
targetUrl = baseUrl.String()
fmt.Println("url: ", targetUrl)
req, err := http.NewRequest(r.Method, targetUrl, r.Body)
if err != nil {
http.Error(w, "Error in request", http.StatusBadRequest)
return
}
// 复制请求头
for name, values := range r.Header {
req.Header[name] = values
}
// 发送请求
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, "Error in forward", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
// 复制响应头
for name, values := range resp.Header {
w.Header()[name] = values
}
// 复制响应体
_, err = io.Copy(w, resp.Body)
if err != nil {
http.Error(w, "Error in copy response", http.StatusInternalServerError)
}
})
// 启动HTTP服务器
log.Fatal(http.ListenAndServe(":8080", nil))
}