fix: CORS 白名单支持 tauri://localhost——修复桌面工具设备列表 Load failed

This commit is contained in:
Logan.Li committed 2026-09-14 22:00:08 +08:00
1 parent 44387835e1
commit 30b87dec62
2 files changed
+17 -17

No files matched your search

+16 -17
View File
@@ -11,7 +11,7 @@ import (
// CORSMiddleware CORS 中间件,使用显式白名单避免携带凭据时放行任意来源。 // Logan.Li
func CORSMiddleware(cfg *config.Config) gin.HandlerFunc {
origins := filterHTTPOrigins(cfg.CORSOrigins)
origins := cfg.CORSOrigins
if len(origins) == 0 {
origins = []string{
"http://localhost:5181",
@@ -20,9 +20,23 @@ func CORSMiddleware(cfg *config.Config) gin.HandlerFunc {
"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: origins,
// 精确白名单匹配(大小写不敏感)。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"},
@@ -30,18 +44,3 @@ func CORSMiddleware(cfg *config.Config) gin.HandlerFunc {
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
}