From 09b446db89f8a7c716abbeb58281bd2899d3aa45 Mon Sep 17 00:00:00 2001 From: Tiago Yamamoto Date: Mon, 22 Dec 2025 11:38:52 -0300 Subject: [PATCH] Add open CORS handling to seeder API --- seeder-api/main.go | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/seeder-api/main.go b/seeder-api/main.go index 84e7420..30129b1 100644 --- a/seeder-api/main.go +++ b/seeder-api/main.go @@ -13,6 +13,21 @@ import ( //go:embed docs/openapi.json var swaggerJSON string +func withCORS(handler http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") + + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + + handler.ServeHTTP(w, r) + }) +} + func main() { godotenv.Load() port := os.Getenv("PORT") @@ -20,7 +35,9 @@ func main() { port = "8080" } - http.HandleFunc("/seed", func(w http.ResponseWriter, r *http.Request) { + mux := http.NewServeMux() + + mux.HandleFunc("/seed", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return @@ -44,7 +61,7 @@ func main() { w.Write([]byte(result)) }) - http.HandleFunc("/swagger.json", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/swagger.json", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return @@ -55,7 +72,7 @@ func main() { }) log.Printf("Seeder API listening on port %s", port) - if err := http.ListenAndServe(":"+port, nil); err != nil { + if err := http.ListenAndServe(":"+port, withCORS(mux)); err != nil { log.Fatalf("Server error: %v", err) } }