diff --git a/backend/internal/api/server.go b/backend/internal/api/server.go index b94943a..fd0cc89 100644 --- a/backend/internal/api/server.go +++ b/backend/internal/api/server.go @@ -15,6 +15,25 @@ type ErrorResponse struct { Error string `json:"error"` } +// CORS middleware for allowing cross-origin requests +func corsMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Allow requests from any origin during development + // In production, you would specify allowed origins + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") + + // Handle preflight requests + if r.Method == "OPTIONS" { + w.WriteHeader(http.StatusOK) + return + } + + next.ServeHTTP(w, r) + }) +} + type Server struct { storage *storage.Storage host string @@ -42,10 +61,13 @@ func (s *Server) Start() error { // Frontend SPA fallback mux.HandleFunc("/", s.handleFrontend) + // Wrap with CORS middleware + handler := corsMiddleware(mux) + addr := fmt.Sprintf("%s:%d", s.host, s.port) logger.Infof("Starting server on %s", addr) - return http.ListenAndServe(addr, mux) + return http.ListenAndServe(addr, handler) } func (s *Server) handleFiles(w http.ResponseWriter, r *http.Request) {