Files
opsx-licence/backend/middleware/cors.go
T
Logan.LiandCursor ac31cc059a fix: 过滤非法 CORS Origin,避免 Docker 启动 panic
gin-contrib/cors 不接受 tauri://,启动时过滤仅保留 http/https。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 12:09:06 +08:00

48 lines
1.3 KiB
Go

package middleware
import (
"backend/config"
"strings"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
// CORSMiddleware CORS 中间件,使用显式白名单避免携带凭据时放行任意来源。 // Logan.Li
func CORSMiddleware(cfg *config.Config) gin.HandlerFunc {
origins := filterHTTPOrigins(cfg.CORSOrigins)
if len(origins) == 0 {
origins = []string{
"http://localhost:5181",
"http://127.0.0.1:5181",
"http://localhost:3000",
"http://127.0.0.1:3000",
}
}
return cors.New(cors.Config{
AllowOrigins: origins,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization", "X-Requested-With"},
ExposeHeaders: []string{"Content-Length", "Content-Type"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
})
}
// filterHTTPOrigins keeps only origins gin-contrib/cors accepts (http/https or *). // Logan.Li
func filterHTTPOrigins(origins []string) []string {
out := make([]string, 0, len(origins))
for _, origin := range origins {
o := strings.TrimSpace(origin)
if o == "" {
continue
}
if o == "*" || strings.HasPrefix(o, "http://") || strings.HasPrefix(o, "https://") {
out = append(out, o)
}
}
return out
}