cors.go 1.4 KB

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