github.com/getong/docker@v1.13.1/api/server/middleware/cors.go (about)

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