cors.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 http
  14. import (
  15. "fmt"
  16. "net/http"
  17. "net/url"
  18. )
  19. type CORSInfo map[string]bool
  20. func NewCORSInfo(origins []string) (*CORSInfo, error) {
  21. // Construct a lookup of all origins.
  22. m := make(map[string]bool)
  23. for _, v := range origins {
  24. if v != "*" {
  25. if _, err := url.Parse(v); err != nil {
  26. return nil, fmt.Errorf("Invalid CORS origin: %s", err)
  27. }
  28. }
  29. m[v] = true
  30. }
  31. info := CORSInfo(m)
  32. return &info, nil
  33. }
  34. // OriginAllowed determines whether the server will allow a given CORS origin.
  35. func (c CORSInfo) OriginAllowed(origin string) bool {
  36. return c["*"] || c[origin]
  37. }
  38. type CORSHandler struct {
  39. Handler http.Handler
  40. Info *CORSInfo
  41. }
  42. // addHeader adds the correct cors headers given an origin
  43. func (h *CORSHandler) addHeader(w http.ResponseWriter, origin string) {
  44. w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
  45. w.Header().Add("Access-Control-Allow-Origin", origin)
  46. w.Header().Add("Access-Control-Allow-Headers", "accept, content-type")
  47. }
  48. // ServeHTTP adds the correct CORS headers based on the origin and returns immediately
  49. // with a 200 OK if the method is OPTIONS.
  50. func (h *CORSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  51. // It is important to flush before leaving the goroutine.
  52. // Or it may miss the latest info written.
  53. defer w.(http.Flusher).Flush()
  54. // Write CORS header.
  55. if h.Info.OriginAllowed("*") {
  56. h.addHeader(w, "*")
  57. } else if origin := req.Header.Get("Origin"); h.Info.OriginAllowed(origin) {
  58. h.addHeader(w, origin)
  59. }
  60. if req.Method == "OPTIONS" {
  61. w.WriteHeader(http.StatusOK)
  62. return
  63. }
  64. h.Handler.ServeHTTP(w, req)
  65. }