From b023fabd90637ad7dcdc920fa9832c41c06b15de Mon Sep 17 00:00:00 2001 From: Sakurasan <1173092237@qq.com> Date: Thu, 30 Mar 2023 18:39:56 +0800 Subject: [PATCH] fix bug --- .gitignore | 1 + router/router.go | 10 +++++----- store/cache.go | 7 +++++-- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index a49eedf..e0f0e0c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ bin/ +test/ *.log *.db diff --git a/router/router.go b/router/router.go index e5dea1d..d9f0199 100644 --- a/router/router.go +++ b/router/router.go @@ -155,7 +155,7 @@ func HandleAddKey(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"error": err.Error()}) return } - c.JSON(http.StatusCreated, k) + c.JSON(http.StatusOK, k) } func HandleDelKey(c *gin.Context) { @@ -191,7 +191,7 @@ func HandleAddUser(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"error": err.Error()}) return } - c.JSON(http.StatusCreated, u) + c.JSON(http.StatusOK, u) } func HandleDelUser(c *gin.Context) { @@ -262,19 +262,19 @@ func HandleProy(c *gin.Context) { // 创建 API 请求 req, err := http.NewRequest(c.Request.Method, baseUrl+c.Request.URL.Path, c.Request.Body) if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) + c.JSON(http.StatusOK, gin.H{"error": err.Error()}) return } req.Header = c.Request.Header 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 } req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", store.FromKeyCacheRandomItem())) resp, err := client.Do(req) if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) + c.JSON(http.StatusOK, gin.H{"error": err.Error()}) return } defer resp.Body.Close() diff --git a/store/cache.go b/store/cache.go index 805d2cf..86e84fa 100644 --- a/store/cache.go +++ b/store/cache.go @@ -24,13 +24,16 @@ func LoadKeysCache() { log.Println(err) return } - for _, key := range keys { - KeysCache.Set(key.Key, true, cache.NoExpiration) + for idx, key := range keys { + KeysCache.Set(to.String(idx), key.Key, cache.NoExpiration) } } func FromKeyCacheRandomItem() string { items := KeysCache.Items() + if len(items) == 1 { + return items[to.String(0)].Object.(string) + } idx := rand.Intn(len(items)) item := items[to.String(idx)] return item.Object.(string)