Created
April 1, 2023 09:30
-
-
Save lidaobing/a7ddf97f0ab78b69bdb64288e3dae3c5 to your computer and use it in GitHub Desktop.
chatgpt proxy with gitlab auth method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"net/http" | |
"net/http/httputil" | |
"os" | |
"strings" | |
) | |
func checkGitlab(token string) bool { | |
url := "https://gitlab.yourcompany.com/api/v4/version" | |
header := map[string]string{ | |
"Authorization": "Bearer " + token, | |
} | |
client := &http.Client{} | |
req, err := http.NewRequest("GET", url, nil) | |
if err != nil { | |
log.Printf("Error creating request: %s\n", err) | |
return false | |
} | |
// 设置 HTTP header | |
for k, v := range header { | |
req.Header.Set(k, v) | |
} | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Printf("Error accessing '%s': %s\n", url, err) | |
return false | |
} | |
defer resp.Body.Close() | |
return resp.StatusCode == http.StatusOK | |
} | |
func hello(w http.ResponseWriter, r *http.Request) { | |
if r.Method == "OPTIONS" { | |
w.Header().Set("Access-Control-Allow-Origin", "*") | |
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") | |
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") | |
w.Header().Set("Access-Control-Expose-Headers", "Authorization") | |
w.WriteHeader(http.StatusOK) | |
return | |
} | |
token, found := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") | |
if !found { | |
http.Error(w, "Unauthorized", http.StatusUnauthorized) | |
return | |
} | |
if !checkGitlab(token) { | |
http.Error(w, "Forbidden", http.StatusForbidden) | |
return | |
} | |
r.Header.Set("Authorization", "Bearer "+os.Getenv("OPENAI_TOKEN")) | |
proxy := &httputil.ReverseProxy{ | |
Director: func(req *http.Request) { | |
req.URL.Scheme = "https" | |
req.URL.Host = "api.openai.com:443" // or your own proxy server | |
req.Host = "api.openai.com" | |
}, | |
} | |
proxy.ServeHTTP(w, r) | |
} | |
func logRequest(handler http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL) | |
handler.ServeHTTP(w, r) | |
}) | |
} | |
func main() { | |
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", hello) | |
log.Println("Server starting on :8080") | |
err := http.ListenAndServe(":8080", logRequest(mux)) | |
log.Fatal(err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment