-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
60 lines (51 loc) · 1.32 KB
/
main.go
File metadata and controls
60 lines (51 loc) · 1.32 KB
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
package main
import (
"net/http"
"net/http/httputil"
"net/url"
)
func main() {
http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("pong"))
if err != nil {
return
}
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
targetUrl := "https://api.openai.com"
target, err := url.Parse(targetUrl)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
r.Header.Set("Authorization", r.Header.Get("Authorization"))
r.Header.Set("Content-Type", "application/json")
r.Host = r.URL.Host
proxy := httputil.NewSingleHostReverseProxy(target)
if r.Header.Get("Accept") == "text/event-stream" {
handleSSE(w, r, proxy)
} else {
proxy.ServeHTTP(w, r)
}
})
err := http.ListenAndServe(":8080", nil)
if err != nil {
return
}
}
func handleSSE(w http.ResponseWriter, r *http.Request, proxy *httputil.ReverseProxy) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
proxy.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
}
// Start proxying SSE request to OpenAI API
done := make(chan bool)
go func() {
proxy.ServeHTTP(w, r)
done <- true
}()
// Wait for SSE request to finish
<-done
}