This commit is contained in:
Sakurasan
2023-03-31 19:55:20 +08:00
parent 10d69263c9
commit cf023aadc1
2 changed files with 39 additions and 3 deletions

View File

@@ -41,9 +41,9 @@ func main() {
// 初始化用户
r.POST("/1/users/init", router.Handleinit)
r.POST("/v1/chat/completions", router.HandleProy)
r.GET("/v1/models", router.HandleProy)
r.GET("/v1/dashboard/billing/credit_grants", router.HandleProy)
r.POST("/v1/chat/completions", router.HandleReverseProxy)
r.GET("/v1/models", router.HandleReverseProxy)
r.GET("/v1/dashboard/billing/credit_grants", router.HandleReverseProxy)
r.Run(":80")
}

View File

@@ -9,6 +9,7 @@ import (
"log"
"net"
"net/http"
"net/http/httputil"
"opencatd-open/store"
"time"
@@ -315,3 +316,38 @@ func HandleProy(c *gin.Context) {
return
}
}
func HandleReverseProxy(c *gin.Context) {
proxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = "https"
req.URL.Host = "api.openai.com"
// req.Header.Set("Authorization", "Bearer YOUR_API_KEY_HERE")
},
}
var localuser bool
auth := c.Request.Header.Get("Authorization")
if len(auth) > 7 && auth[:7] == "Bearer " {
if store.IsExistAuthCache(auth[7:]) {
localuser = true
}
}
// req, err := http.NewRequest(c.Request.Method, baseUrl+c.Request.URL.Path, c.Request.Body)
// if err != nil {
// c.JSON(http.StatusOK, gin.H{"error": err.Error()})
// return
// }
// req.Header = c.Request.Header
if localuser {
if store.KeysCache.ItemCount() == 0 {
c.JSON(http.StatusOK, gin.H{"error": "No Api-Key Available"})
return
}
c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", store.FromKeyCacheRandomItem()))
}
proxy.ServeHTTP(c.Writer, c.Request)
}