gohorsejobs/backend/internal/middleware/cors.go
Tiago Yamamoto 7934afcf0d docs: complete project documentation overhaul
- Add comprehensive root README with badges, architecture diagram, and setup guide
- Update backend README with security middlewares and endpoint documentation
- Update frontend README with design system and page structure
- Update seeder-api README with generated data and credentials
- Add internal module READMEs (middleware, handlers, components)
- Document Clean Architecture layers and request flow
- Add environment variables reference table
2025-12-09 19:36:36 -03:00

44 lines
1.1 KiB
Go

package middleware
import (
"net/http"
"os"
"strings"
)
// CORSMiddleware handles Cross-Origin Resource Sharing
// IMPORTANT: Configure CORS_ORIGINS env var in production
func CORSMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origins := os.Getenv("CORS_ORIGINS")
if origins == "" {
origins = "http://localhost:3000"
}
origin := r.Header.Get("Origin")
allowOrigin := ""
// Check if origin is in allowed list
for _, o := range strings.Split(origins, ",") {
if strings.TrimSpace(o) == origin {
allowOrigin = origin
break
}
}
if allowOrigin != "" {
w.Header().Set("Access-Control-Allow-Origin", allowOrigin)
}
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-CSRF-Token")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}