github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/api/server/middleware/cors.go (about)

     1  package middleware // import "github.com/docker/docker/api/server/middleware"
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  
     7  	"github.com/docker/docker/api/types/registry"
     8  	"github.com/sirupsen/logrus"
     9  )
    10  
    11  // CORSMiddleware injects CORS headers to each request
    12  // when it's configured.
    13  type CORSMiddleware struct {
    14  	defaultHeaders string
    15  }
    16  
    17  // NewCORSMiddleware creates a new CORSMiddleware with default headers.
    18  func NewCORSMiddleware(d string) CORSMiddleware {
    19  	return CORSMiddleware{defaultHeaders: d}
    20  }
    21  
    22  // WrapHandler returns a new handler function wrapping the previous one in the request chain.
    23  func (c CORSMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
    24  	return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
    25  		// If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
    26  		// otherwise, all head values will be passed to HTTP handler
    27  		corsHeaders := c.defaultHeaders
    28  		if corsHeaders == "" {
    29  			corsHeaders = "*"
    30  		}
    31  
    32  		logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
    33  		w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
    34  		w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, "+registry.AuthHeader)
    35  		w.Header().Add("Access-Control-Allow-Methods", "HEAD, GET, POST, DELETE, PUT, OPTIONS")
    36  		return handler(ctx, w, r, vars)
    37  	}
    38  }