cors.go 900 B

123456789101112131415161718192021222324252627282930313233
  1. package cors
  2. import (
  3. "net/http"
  4. "strings"
  5. log "github.com/sirupsen/logrus"
  6. )
  7. func AllowCors(h http.Handler) http.Handler {
  8. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  9. if origin := r.Header.Get("Origin"); origin != "" {
  10. log.Infof("Setting CORS header: %v", origin)
  11. w.Header().Set("Access-Control-Allow-Origin", origin)
  12. if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
  13. preflightHandler(w, r)
  14. return
  15. }
  16. }
  17. h.ServeHTTP(w, r)
  18. })
  19. }
  20. func preflightHandler(w http.ResponseWriter, r *http.Request) {
  21. log.Infof("preflight request for %s", r.URL.Path)
  22. headers := []string{"Content-Type", "Accept"}
  23. w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ","))
  24. methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"}
  25. w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
  26. }