feat(cors): implement cors
This commit is contained in:
parent
9e2b38e205
commit
15ad7a2fb7
2 changed files with 58 additions and 1 deletions
|
|
@ -26,6 +26,36 @@ type Server struct {
|
|||
db *sql.DB
|
||||
}
|
||||
|
||||
var allowedOrigins = map[string]struct{}{
|
||||
"http://localhost:4173": {},
|
||||
"http://127.0.0.1:4173": {},
|
||||
"http://localhost:5173": {},
|
||||
"http://127.0.0.1:5173": {},
|
||||
}
|
||||
|
||||
// corsMiddleware adds the headers needed for cross-origin requests from the frontend.
|
||||
func corsMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if _, ok := allowedOrigins[origin]; ok {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Vary", "Origin")
|
||||
}
|
||||
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Access-Control-Max-Age", "86400")
|
||||
|
||||
// Handle preflight without hitting the underlying handlers.
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Ingest handler
|
||||
func (s *Server) ingestHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var event DroneEvent
|
||||
|
|
@ -163,7 +193,7 @@ func main() {
|
|||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: mux,
|
||||
Handler: corsMiddleware(mux),
|
||||
}
|
||||
|
||||
// Graceful shutdown
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue