handlers.go 815 B

123456789101112131415161718192021222324252627
  1. package rest
  2. import "net/http"
  3. const (
  4. allowOrigin = "Access-Control-Allow-Origin"
  5. allOrigins = "*"
  6. allowMethods = "Access-Control-Allow-Methods"
  7. allowHeaders = "Access-Control-Allow-Headers"
  8. headers = "Content-Type, Content-Length, Origin"
  9. methods = "GET, HEAD, POST, PATCH, PUT, DELETE"
  10. )
  11. // CorsHandler handles cross domain OPTIONS requests.
  12. // At most one origin can be specified, other origins are ignored if given.
  13. func CorsHandler(origins ...string) http.Handler {
  14. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  15. if len(origins) > 0 {
  16. w.Header().Set(allowOrigin, origins[0])
  17. } else {
  18. w.Header().Set(allowOrigin, allOrigins)
  19. }
  20. w.Header().Set(allowMethods, methods)
  21. w.Header().Set(allowHeaders, headers)
  22. w.WriteHeader(http.StatusNoContent)
  23. })
  24. }