hako/internal/server/middleware/cors.go
2026-01-12 19:35:18 +01:00

32 lines
1,021 B
Go

package middleware
import (
"net/http"
)
// CORSMiddleware creates a middleware that handles CORS headers
// Allows requests from the Vite dev server (localhost:5173)
func CORSMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set CORS headers
origin := r.Header.Get("Origin")
// Allow requests from Vite dev server
if origin == "http://localhost:5173" || origin == "http://127.0.0.1:5173" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
// Handle preflight OPTIONS requests
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
// Continue with the request
next.ServeHTTP(w, r)
})
}
}