|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "net/http/httputil" |
| 6 | + "net/url" |
| 7 | +) |
| 8 | + |
| 9 | +func main() { |
| 10 | + http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) { |
| 11 | + _, err := w.Write([]byte("pong")) |
| 12 | + if err != nil { |
| 13 | + return |
| 14 | + } |
| 15 | + }) |
| 16 | + |
| 17 | + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 18 | + targetUrl := "https://api.openai.com" |
| 19 | + target, err := url.Parse(targetUrl) |
| 20 | + if err != nil { |
| 21 | + http.Error(w, "Internal Server Error", http.StatusInternalServerError) |
| 22 | + return |
| 23 | + } |
| 24 | + r.Header.Set("Authorization", r.Header.Get("Authorization")) |
| 25 | + r.Header.Set("Content-Type", "application/json") |
| 26 | + r.Host = r.URL.Host |
| 27 | + |
| 28 | + proxy := httputil.NewSingleHostReverseProxy(target) |
| 29 | + |
| 30 | + if r.Header.Get("Accept") == "text/event-stream" { |
| 31 | + handleSSE(w, r, proxy) |
| 32 | + } else { |
| 33 | + proxy.ServeHTTP(w, r) |
| 34 | + } |
| 35 | + }) |
| 36 | + |
| 37 | + err := http.ListenAndServe(":8080", nil) |
| 38 | + if err != nil { |
| 39 | + return |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +func handleSSE(w http.ResponseWriter, r *http.Request, proxy *httputil.ReverseProxy) { |
| 44 | + w.Header().Set("Content-Type", "text/event-stream") |
| 45 | + w.Header().Set("Cache-Control", "no-cache") |
| 46 | + w.Header().Set("Connection", "keep-alive") |
| 47 | + |
| 48 | + proxy.Transport = &http.Transport{ |
| 49 | + Proxy: http.ProxyFromEnvironment, |
| 50 | + } |
| 51 | + // Start proxying SSE request to OpenAI API |
| 52 | + done := make(chan bool) |
| 53 | + go func() { |
| 54 | + proxy.ServeHTTP(w, r) |
| 55 | + done <- true |
| 56 | + }() |
| 57 | + |
| 58 | + // Wait for SSE request to finish |
| 59 | + <-done |
| 60 | +} |
0 commit comments