github.com/boynux/docker@v1.11.0-rc4/api/server/middleware/cors.go (about)

     1  package middleware
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/Sirupsen/logrus"
     7  	"github.com/docker/docker/api/server/httputils"
     8  	"golang.org/x/net/context"
     9  )
    10  
    11  // NewCORSMiddleware creates a new CORS middleware.
    12  func NewCORSMiddleware(defaultHeaders string) Middleware {
    13  	return func(handler httputils.APIFunc) httputils.APIFunc {
    14  		return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
    15  			// If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
    16  			// otherwise, all head values will be passed to HTTP handler
    17  			corsHeaders := defaultHeaders
    18  			if corsHeaders == "" {
    19  				corsHeaders = "*"
    20  			}
    21  
    22  			writeCorsHeaders(w, r, corsHeaders)
    23  			return handler(ctx, w, r, vars)
    24  		}
    25  	}
    26  }
    27  
    28  func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
    29  	logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
    30  	w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
    31  	w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
    32  	w.Header().Add("Access-Control-Allow-Methods", "HEAD, GET, POST, DELETE, PUT, OPTIONS")
    33  }