chore: 初始化仓库基线(AGENTS.md、git 规范、敏感文件排除)
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CORS 跨域中间件,限制允许的来源、方法和头
|
||||
func CORS() gin.HandlerFunc {
|
||||
// 允许的来源:同源、本地开发、Tailscale 网段、局域网
|
||||
allowedOrigins := []string{
|
||||
"http://localhost:5174",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:5174",
|
||||
"http://127.0.0.1:3000",
|
||||
}
|
||||
|
||||
isAllowed := func(origin string) bool {
|
||||
for _, o := range allowedOrigins {
|
||||
if origin == o {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// 允许 Tailscale 100.x.x.x 和局域网 192.168.x.x 访问
|
||||
if strings.HasPrefix(origin, "http://100.") || strings.HasPrefix(origin, "http://192.168.") ||
|
||||
strings.HasPrefix(origin, "http://113.") || strings.HasPrefix(origin, "http://115.") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
return func(c *gin.Context) {
|
||||
origin := c.GetHeader("Origin")
|
||||
if origin != "" && isAllowed(origin) {
|
||||
c.Header("Access-Control-Allow-Origin", origin)
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-API-Key")
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
c.Header("Vary", "Origin")
|
||||
}
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user