feat(cors): implement cors

This commit is contained in:
js0ny 2025-12-06 11:40:29 +00:00
parent 9e2b38e205
commit 15ad7a2fb7
2 changed files with 58 additions and 1 deletions

View file

@ -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

View file

@ -0,0 +1,27 @@
package io.github.js0ny.ilp_coursework.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Global CORS configuration so the frontend running on a different port can call the REST API.
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
private static final String[] ALLOWED_ORIGINS = new String[] {
"http://localhost:4173",
"http://127.0.0.1:4173",
"http://localhost:5173",
"http://127.0.0.1:5173"
};
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(ALLOWED_ORIGINS)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH")
.allowedHeaders("*");
}
}