cors.go 1.5 KB

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