cors_handler.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright 2013 CoreOS Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package server
  14. import (
  15. "fmt"
  16. "net/http"
  17. "net/url"
  18. "github.com/gorilla/mux"
  19. )
  20. type corsHandler struct {
  21. router *mux.Router
  22. corsOrigins map[string]bool
  23. }
  24. // AllowOrigins sets a comma-delimited list of origins that are allowed.
  25. func (s *corsHandler) AllowOrigins(origins []string) error {
  26. // Construct a lookup of all origins.
  27. m := make(map[string]bool)
  28. for _, v := range origins {
  29. if v != "*" {
  30. if _, err := url.Parse(v); err != nil {
  31. return fmt.Errorf("Invalid CORS origin: %s", err)
  32. }
  33. }
  34. m[v] = true
  35. }
  36. s.corsOrigins = m
  37. return nil
  38. }
  39. // OriginAllowed determines whether the server will allow a given CORS origin.
  40. func (c *corsHandler) OriginAllowed(origin string) bool {
  41. return c.corsOrigins["*"] || c.corsOrigins[origin]
  42. }
  43. // addHeader adds the correct cors headers given an origin
  44. func (h *corsHandler) addHeader(w http.ResponseWriter, origin string) {
  45. w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
  46. w.Header().Add("Access-Control-Allow-Origin", origin)
  47. }
  48. // ServeHTTP adds the correct CORS headers based on the origin and returns immediatly
  49. // with a 200 OK if the method is OPTIONS.
  50. func (h *corsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  51. // Write CORS header.
  52. if h.OriginAllowed("*") {
  53. h.addHeader(w, "*")
  54. } else if origin := req.Header.Get("Origin"); h.OriginAllowed(origin) {
  55. h.addHeader(w, origin)
  56. }
  57. if req.Method == "OPTIONS" {
  58. w.WriteHeader(http.StatusOK)
  59. return
  60. }
  61. h.router.ServeHTTP(w, req)
  62. }