Files
opsx-licence/backend/middleware/cors.go
T

47 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 := 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",
}
}
allowed := make([]string, 0, len(origins))
for _, o := range origins {
allowed = append(allowed, strings.ToLower(strings.TrimSpace(o)))
}
return cors.New(cors.Config{
// 精确白名单匹配(大小写不敏感)。AllowOrigins 只接受 http/https,
// 而 macOS Tauri WebView 的 Origin 是 tauri://localhost,须用函数匹配 // Logan.Li
AllowOriginFunc: func(origin string) bool {
o := strings.ToLower(strings.TrimSpace(origin))
for _, a := range allowed {
if o == a {
return true
}
}
return false
},
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,
})
}