cors.go 1.1 KB

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