madipo2611 eae5cd2997
All checks were successful
continuous-integration/drone/push Build is passing
v0.0.23 исправлен cors и ws_auth
2025-08-19 23:05:55 +03:00

61 lines
1.7 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 (
"github.com/gorilla/websocket"
"net/http"
"strings"
)
// CORS middleware настраивает политику кросс-доменных запросов
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) {
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")
// Для WebSocket тоже нужны CORS заголовки
if websocket.IsWebSocketUpgrade(r) {
w.Header().Set("Access-Control-Allow-Headers",
"Authorization, Sec-WebSocket-Protocol, Sec-WebSocket-Version, Sec-WebSocket-Key")
} else {
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
}
// Разрешаем все источники в development
if len(allowedOrigins) == 1 && allowedOrigins[0] == "*" {
return true
}
// Точноe сравнение с разрешенными доменами
for _, allowed := range allowedOrigins {
if strings.EqualFold(origin, allowed) {
return true
}
}
return false
}