madipo2611 3b7cc31449
All checks were successful
continuous-integration/drone/push Build is passing
v0.0.18.2 Добавлен WSAuthMiddleware
2025-08-14 12:44:03 +03:00

60 lines
1.5 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) {
if websocket.IsWebSocketUpgrade(r) {
next.ServeHTTP(w, r)
return
}
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
}
// Разрешаем все источники в development
if len(allowedOrigins) == 1 && allowedOrigins[0] == "*" {
return true
}
// Точноe сравнение с разрешенными доменами
for _, allowed := range allowedOrigins {
if strings.EqualFold(origin, allowed) {
return true
}
}
return false
}