add cors support

This commit is contained in:
2026-01-23 20:20:32 -05:00
parent 301c19afe1
commit 3a7a036134
5 changed files with 71 additions and 29 deletions

View File

@@ -15,6 +15,7 @@ import (
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/cors"
"github.com/rs/zerolog"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel/metric"
@@ -146,6 +147,29 @@ func prepHTTPServer(opts *opts.AppHTTP) *http.Server {
handler = loggingMiddleware(opts.Ctx, handler)
}
// Apply CORS middleware if enabled
if cfg.HTTP.CORSEnabled {
allowedOrigins := cfg.HTTP.CORSAllowedOrigins
if len(allowedOrigins) == 0 {
allowedOrigins = []string{"*"}
}
corsHandler := cors.New(cors.Options{
AllowedOrigins: allowedOrigins,
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"*"},
AllowCredentials: cfg.HTTP.CORSAllowCredentials,
AllowPrivateNetwork: cfg.HTTP.CORSAllowPrivateNetwork,
})
handler = corsHandler.Handler(handler)
l.Info().
Strs("allowedOrigins", allowedOrigins).
Bool("allowCredentials", cfg.HTTP.CORSAllowCredentials).
Bool("allowPrivateNetwork", cfg.HTTP.CORSAllowPrivateNetwork).
Msg("CORS enabled")
}
return &http.Server{
Addr: cfg.HTTP.Listen,
ReadTimeout: readTimeout,