2026-03-09 21:28:58 +08:00
|
|
|
package middleware
|
|
|
|
|
|
2026-03-19 13:49:51 +08:00
|
|
|
import (
|
|
|
|
|
"net/http"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var allowedOrigins = []string{
|
2026-04-22 16:40:11 +08:00
|
|
|
"https://withyou.littlelan.cn",
|
2026-03-19 22:46:21 +08:00
|
|
|
"https://admin.littlelan.cn",
|
|
|
|
|
"https://browser.littlelan.cn",
|
2026-03-19 13:49:51 +08:00
|
|
|
"http://localhost:3000",
|
|
|
|
|
"http://localhost:5173",
|
|
|
|
|
"http://127.0.0.1:3000",
|
|
|
|
|
"http://127.0.0.1:5173",
|
|
|
|
|
}
|
2026-03-09 21:28:58 +08:00
|
|
|
|
2026-03-19 22:46:21 +08:00
|
|
|
func isAllowedOrigin(origin string) bool {
|
|
|
|
|
for _, o := range allowedOrigins {
|
|
|
|
|
if o == origin {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if strings.HasPrefix(origin, "http://localhost") || strings.HasPrefix(origin, "http://127.0.0.1") {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if strings.HasPrefix(origin, "https://") && strings.HasSuffix(origin, ".littlelan.cn") {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-09 21:28:58 +08:00
|
|
|
func CORS() gin.HandlerFunc {
|
|
|
|
|
return func(c *gin.Context) {
|
2026-03-19 13:49:51 +08:00
|
|
|
origin := c.GetHeader("Origin")
|
|
|
|
|
|
2026-03-19 22:46:21 +08:00
|
|
|
if isAllowedOrigin(origin) {
|
|
|
|
|
c.Header("Access-Control-Allow-Origin", origin)
|
2026-03-19 13:49:51 +08:00
|
|
|
c.Header("Access-Control-Allow-Credentials", "true")
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-09 21:28:58 +08:00
|
|
|
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
|
|
|
|
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization, Connection, Upgrade, Sec-WebSocket-Key, Sec-WebSocket-Version, Sec-WebSocket-Protocol, Sec-WebSocket-Extensions")
|
|
|
|
|
c.Header("Access-Control-Expose-Headers", "Content-Length, Connection, Upgrade")
|
|
|
|
|
|
|
|
|
|
if c.Request.Method == "OPTIONS" {
|
2026-03-19 13:49:51 +08:00
|
|
|
c.AbortWithStatus(http.StatusNoContent)
|
2026-03-09 21:28:58 +08:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.Next()
|
|
|
|
|
}
|
|
|
|
|
}
|