madipo2611 6b9cdeba55
All checks were successful
continuous-integration/drone/push Build is passing
v0.0.17 Переработан websocket
2025-08-11 00:22:16 +03:00

55 lines
1.4 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) {
origin := r.Header.Get("Origin")
if r.Header.Get("Upgrade") == "websocket" {
next.ServeHTTP(w, r)
return
}
// Проверяем, разрешен ли источник
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")
}
// Обрабатываем предварительные 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
}