madipo2611 2145affdac
All checks were successful
continuous-integration/drone/push Build is passing
v0.0.17.3 Переработан websocket, добавлена обработка ping/pong
2025-08-11 15:52:46 +03:00

59 lines
1.6 KiB
Go

package middleware
import (
"net/http"
"strings"
)
func CORS(allowedOrigins []string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Особые правила для WebSocket
if r.Header.Get("Upgrade") == "websocket" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "*")
next.ServeHTTP(w, r)
return
}
// Стандартная CORS логика для других запросов
origin := r.Header.Get("Origin")
if isOriginAllowed(origin, allowedOrigins) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, Authorization, bypass-auth")
w.Header().Set("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
}
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
}
// isOriginAllowed проверяет разрешен ли домен для CORS
func isOriginAllowed(origin string, allowedOrigins []string) bool {
if origin == "" {
return false
}
if len(allowedOrigins) == 1 && allowedOrigins[0] == "*" {
return true
}
for _, allowed := range allowedOrigins {
if strings.EqualFold(origin, allowed) {
return true
}
}
return false
}