This commit is contained in:
Sakurasan
2023-03-30 18:39:56 +08:00
parent 6a6fca6c88
commit b023fabd90
3 changed files with 11 additions and 7 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
bin/ bin/
test/
*.log *.log
*.db *.db

View File

@@ -155,7 +155,7 @@ func HandleAddKey(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"error": err.Error()}) c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return return
} }
c.JSON(http.StatusCreated, k) c.JSON(http.StatusOK, k)
} }
func HandleDelKey(c *gin.Context) { func HandleDelKey(c *gin.Context) {
@@ -191,7 +191,7 @@ func HandleAddUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"error": err.Error()}) c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return return
} }
c.JSON(http.StatusCreated, u) c.JSON(http.StatusOK, u)
} }
func HandleDelUser(c *gin.Context) { func HandleDelUser(c *gin.Context) {
@@ -262,19 +262,19 @@ func HandleProy(c *gin.Context) {
// 创建 API 请求 // 创建 API 请求
req, err := http.NewRequest(c.Request.Method, baseUrl+c.Request.URL.Path, c.Request.Body) req, err := http.NewRequest(c.Request.Method, baseUrl+c.Request.URL.Path, c.Request.Body)
if err != nil { if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return return
} }
req.Header = c.Request.Header req.Header = c.Request.Header
if store.KeysCache.ItemCount() == 0 { if store.KeysCache.ItemCount() == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "No Api-Key Available"}) c.JSON(http.StatusOK, gin.H{"error": "No Api-Key Available"})
return return
} }
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", store.FromKeyCacheRandomItem())) req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", store.FromKeyCacheRandomItem()))
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return return
} }
defer resp.Body.Close() defer resp.Body.Close()

View File

@@ -24,13 +24,16 @@ func LoadKeysCache() {
log.Println(err) log.Println(err)
return return
} }
for _, key := range keys { for idx, key := range keys {
KeysCache.Set(key.Key, true, cache.NoExpiration) KeysCache.Set(to.String(idx), key.Key, cache.NoExpiration)
} }
} }
func FromKeyCacheRandomItem() string { func FromKeyCacheRandomItem() string {
items := KeysCache.Items() items := KeysCache.Items()
if len(items) == 1 {
return items[to.String(0)].Object.(string)
}
idx := rand.Intn(len(items)) idx := rand.Intn(len(items))
item := items[to.String(idx)] item := items[to.String(idx)]
return item.Object.(string) return item.Object.(string)