From acaaa1eddbc0ec0577b122c5da77212f692ea067 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Mon, 17 Jul 2023 14:34:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=B7=A8=E5=9F=9F=E6=94=AF?= =?UTF-8?q?=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/main.go b/main.go index b5be839..997a2eb 100644 --- a/main.go +++ b/main.go @@ -687,6 +687,24 @@ func checkKeyMid() gin.HandlerFunc { } } +func Cors() gin.HandlerFunc { + return func(c *gin.Context) { + method := c.Request.Method + origin := c.Request.Header.Get("Origin") + if origin != "" { + c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名 + c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") + c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") + c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type") + c.Header("Access-Control-Allow-Credentials", "true") + } + if method == "OPTIONS" { + c.AbortWithStatus(http.StatusNoContent) + } + c.Next() + } +} + func main() { // 禁用控制台颜色,将日志写入文件时不需要控制台颜色。 @@ -703,6 +721,8 @@ func main() { r := gin.Default() + r.Use(Cors()) + r.GET("/dashboard/billing/credit_grants", checkKeyMid(), balance) r.GET("/v1/models", handleGetModels)