add cors support
This commit is contained in:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user