saveinmed/backend/internal/http/middleware/cors.go
Gabbriiel 90467db1ec refactor: substitui backend Medusa por backend Go e corrige testes do marketplace
- Remove backend Medusa.js (TypeScript) e substitui pelo backend Go (saveinmed-performance-core)
- Corrige testes auth.test.ts: alinha paths de API (v1/ sem barra inicial) e campo access_token
- Corrige GroupedProductCard.test.tsx: ajusta distância formatada (toFixed) e troca userEvent por fireEvent com fakeTimers
- Corrige AuthContext.test.tsx: usa vi.hoisted() para mocks e corrige parênteses no waitFor

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 04:56:37 -06:00

58 lines
1.8 KiB
Go

package middleware
import (
"net/http"
"strings"
)
// CORSConfig holds the configuration for CORS middleware.
type CORSConfig struct {
AllowedOrigins []string
}
// CORS adds Cross-Origin Resource Sharing headers to the response.
// If allowedOrigins contains "*", it allows all origins.
// Otherwise, it checks if the request origin is in the allowed list.
func CORSWithConfig(cfg CORSConfig) func(http.Handler) http.Handler {
allowAll := false
originsMap := make(map[string]bool)
for _, origin := range cfg.AllowedOrigins {
if origin == "*" {
allowAll = true
break
}
originsMap[strings.ToLower(origin)] = true
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if allowAll {
w.Header().Set("Access-Control-Allow-Origin", "*")
} else if origin != "" && originsMap[strings.ToLower(origin)] {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Vary", "Origin")
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, Accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Max-Age", "86400")
// Handle preflight requests
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
}
// CORS is a compatibility wrapper that allows all origins.
// Deprecated: Use CORSWithConfig for more control.
func CORS(next http.Handler) http.Handler {
return CORSWithConfig(CORSConfig{AllowedOrigins: []string{"*"}})(next)
}