cors.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. Copyright 2014 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 cors
  14. import (
  15. "fmt"
  16. "net/http"
  17. "net/url"
  18. "strings"
  19. )
  20. type CORSInfo map[string]bool
  21. // CORSInfo implements the flag.Value interface to allow users to define a list of CORS origins
  22. func (ci *CORSInfo) Set(s string) error {
  23. m := make(map[string]bool)
  24. for _, v := range strings.Split(s, ",") {
  25. v = strings.TrimSpace(v)
  26. if v == "" {
  27. continue
  28. }
  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. *ci = CORSInfo(m)
  37. return nil
  38. }
  39. func (ci *CORSInfo) String() string {
  40. o := make([]string, 0)
  41. for k, _ := range *ci {
  42. o = append(o, k)
  43. }
  44. return strings.Join(o, ",")
  45. }
  46. // OriginAllowed determines whether the server will allow a given CORS origin.
  47. func (c CORSInfo) OriginAllowed(origin string) bool {
  48. return c["*"] || c[origin]
  49. }
  50. type CORSHandler struct {
  51. Handler http.Handler
  52. Info *CORSInfo
  53. }
  54. // addHeader adds the correct cors headers given an origin
  55. func (h *CORSHandler) addHeader(w http.ResponseWriter, origin string) {
  56. w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
  57. w.Header().Add("Access-Control-Allow-Origin", origin)
  58. w.Header().Add("Access-Control-Allow-Headers", "accept, content-type")
  59. }
  60. // ServeHTTP adds the correct CORS headers based on the origin and returns immediately
  61. // with a 200 OK if the method is OPTIONS.
  62. func (h *CORSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  63. // It is important to flush before leaving the goroutine.
  64. // Or it may miss the latest info written.
  65. defer w.(http.Flusher).Flush()
  66. // Write CORS header.
  67. if h.Info.OriginAllowed("*") {
  68. h.addHeader(w, "*")
  69. } else if origin := req.Header.Get("Origin"); h.Info.OriginAllowed(origin) {
  70. h.addHeader(w, origin)
  71. }
  72. if req.Method == "OPTIONS" {
  73. w.WriteHeader(http.StatusOK)
  74. return
  75. }
  76. h.Handler.ServeHTTP(w, req)
  77. }