From b441e60b90c521ad948b725140f6d5acc8e252db Mon Sep 17 00:00:00 2001 From: Oshan Date: Mon, 6 Apr 2026 18:57:57 +0530 Subject: [PATCH] Fix CORS origin handling for Railway frontend --- backend/internal/middleware/cors/cors.go | 53 ++++++++++++++++++++---- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/backend/internal/middleware/cors/cors.go b/backend/internal/middleware/cors/cors.go index d005de0..8d932c9 100644 --- a/backend/internal/middleware/cors/cors.go +++ b/backend/internal/middleware/cors/cors.go @@ -1,23 +1,25 @@ package middleware -import -("net/http" - +import ( + "net/http" + "os" + "strings" ) func CORS(next http.Handler) http.Handler { + allowedOrigins := allowedOriginsFromEnv() return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - url:="https://scintillating-commitment-production-2429.up.railway.app/" - w.Header().Set("Access-Control-Allow-Origin", url) + origin := strings.TrimSpace(r.Header.Get("Origin")) + if isAllowedOrigin(origin, allowedOrigins) { + w.Header().Set("Access-Control-Allow-Origin", origin) + w.Header().Add("Vary", "Origin") + } w.Header().Set("Access-Control-Allow-Credentials", "true") - w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type") - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS") - // preflight if r.Method == http.MethodOptions { w.WriteHeader(http.StatusOK) return @@ -26,3 +28,38 @@ func CORS(next http.Handler) http.Handler { next.ServeHTTP(w, r) }) } + +func allowedOriginsFromEnv() map[string]struct{} { + origins := map[string]struct{}{} + + for _, envKey := range []string{"CLIENT_URL", "CORS_ALLOWED_ORIGINS"} { + raw := strings.TrimSpace(os.Getenv(envKey)) + if raw == "" { + continue + } + + for _, candidate := range strings.Split(raw, ",") { + origin := strings.TrimSpace(strings.TrimSuffix(candidate, "/")) + if origin == "" { + continue + } + origins[origin] = struct{}{} + } + } + + if len(origins) == 0 { + origins["http://localhost:5173"] = struct{}{} + } + + return origins +} + +func isAllowedOrigin(origin string, allowed map[string]struct{}) bool { + if origin == "" { + return false + } + + normalized := strings.TrimSuffix(strings.TrimSpace(origin), "/") + _, ok := allowed[normalized] + return ok +}