package middleware import ( "net/http" "github.com/rs/cors" ) // CORSConfig defines the configuration options for CORS middleware type CORSConfig struct { // AllowedOrigins defines the origins that are allowed to access the resource AllowedOrigins []string // AllowedMethods defines the HTTP methods that are allowed AllowedMethods []string // AllowedHeaders defines the headers that are allowed in requests AllowedHeaders []string // ExposedHeaders defines the headers that can be read by the browser ExposedHeaders []string // AllowCredentials defines whether cookies, HTTP authentication and client SSL // certificates can be transmitted in cross-origin requests AllowCredentials bool // MaxAge defines how long (in seconds) the results of a preflight request can be cached MaxAge int } // DefaultCORSConfig returns a default configuration for CORS middleware func DefaultCORSConfig() CORSConfig { return CORSConfig{ AllowedOrigins: []string{}, AllowedMethods: []string{"GET"}, AllowedHeaders: []string{}, ExposedHeaders: []string{}, AllowCredentials: false, MaxAge: 0, } } // CORS middleware handles Cross-Origin Resource Sharing func CORS(config CORSConfig) Middleware { c := cors.New(cors.Options{ AllowedOrigins: config.AllowedOrigins, AllowedMethods: config.AllowedMethods, AllowedHeaders: config.AllowedHeaders, ExposedHeaders: config.ExposedHeaders, AllowCredentials: config.AllowCredentials, MaxAge: config.MaxAge, }) return func(next http.Handler) http.Handler { return c.Handler(next) } }