madipo2611 6f5298d420 v0.0.3
2025-05-03 02:37:08 +03:00

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