feat: add CORS middleware to backend server

Add cross-origin resource sharing support to the backend API to fix
frontend console errors when accessing resources from different origins.
The middleware handles preflight requests and includes necessary CORS
headers for API endpoints.

Fixes: Cross-Origin Request Blocked error
This commit is contained in:
2026-02-05 18:21:47 -05:00
parent 8e04f51b2d
commit d2d8370c95

View File

@@ -15,6 +15,25 @@ type ErrorResponse struct {
Error string `json:"error"` 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 { type Server struct {
storage *storage.Storage storage *storage.Storage
host string host string
@@ -42,10 +61,13 @@ func (s *Server) Start() error {
// Frontend SPA fallback // Frontend SPA fallback
mux.HandleFunc("/", s.handleFrontend) mux.HandleFunc("/", s.handleFrontend)
// Wrap with CORS middleware
handler := corsMiddleware(mux)
addr := fmt.Sprintf("%s:%d", s.host, s.port) addr := fmt.Sprintf("%s:%d", s.host, s.port)
logger.Infof("Starting server on %s", addr) 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) { func (s *Server) handleFiles(w http.ResponseWriter, r *http.Request) {