Skip to content

Commit 3ffff94

Browse files
committed
fix: add CORS headers to serverless health and error responses
1 parent 61ce056 commit 3ffff94

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

api/index.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"context"
55
"encoding/json"
66
"net/http"
7+
"os"
8+
"strings"
79
"sync"
810

911
"eventra/bootstrap"
@@ -16,6 +18,12 @@ var (
1618
)
1719

1820
func Handler(w http.ResponseWriter, r *http.Request) {
21+
applyCORS(w, r)
22+
if r.Method == http.MethodOptions {
23+
w.WriteHeader(http.StatusNoContent)
24+
return
25+
}
26+
1927
if r.URL.Path == "/health" {
2028
w.Header().Set("Content-Type", "application/json")
2129
w.WriteHeader(http.StatusOK)
@@ -38,3 +46,41 @@ func Handler(w http.ResponseWriter, r *http.Request) {
3846

3947
router.ServeHTTP(w, r)
4048
}
49+
50+
func applyCORS(w http.ResponseWriter, r *http.Request) {
51+
origin := strings.TrimSpace(r.Header.Get("Origin"))
52+
if origin == "" {
53+
return
54+
}
55+
56+
if !isAllowedOrigin(origin) {
57+
return
58+
}
59+
60+
w.Header().Set("Access-Control-Allow-Origin", origin)
61+
w.Header().Set("Vary", "Origin")
62+
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
63+
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
64+
}
65+
66+
func isAllowedOrigin(origin string) bool {
67+
allowed := []string{"http://localhost:5173", "http://127.0.0.1:5173", "https://eventra-auth.vercel.app"}
68+
69+
if raw := strings.TrimSpace(os.Getenv("CORS_ALLOWED_ORIGINS")); raw != "" {
70+
allowed = allowed[:0]
71+
for _, part := range strings.Split(raw, ",") {
72+
trimmed := strings.TrimSpace(part)
73+
if trimmed != "" {
74+
allowed = append(allowed, trimmed)
75+
}
76+
}
77+
}
78+
79+
for _, candidate := range allowed {
80+
if strings.EqualFold(strings.TrimSpace(candidate), origin) {
81+
return true
82+
}
83+
}
84+
85+
return false
86+
}

0 commit comments

Comments
 (0)