修改后端初始化

This commit is contained in:
2025-10-04 20:48:50 +08:00
parent 2dea178fde
commit 2afbafa192
13 changed files with 289 additions and 146 deletions

39
server/middleware/cors.go Normal file
View File

@@ -0,0 +1,39 @@
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
func CorsMiddleware(cfg *config.ServerConfig) gin.HandlerFunc {
return func(c *gin.Context) {
// 处理跨域请求头
origin := c.Request.Header.Get("Origin")
if origin != "" && isAllowedOrigin(origin, cfg.AllowedOrigins) {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
}
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
// 处理预检请求
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(http.StatusOK)
return
}
c.Next()
}
}
// 检查来源是否在允许的列表中
func isAllowedOrigin(origin string, allowedOrigins []string) bool {
for _, allowed := range allowedOrigins {
if allowed == "*" || allowed == origin {
return true
}
}
return false
}