cors.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. )
  19. type corsInfo struct {
  20. origins map[string]bool
  21. }
  22. func NewCORSInfo(origins []string) (*corsInfo, error) {
  23. // Construct a lookup of all origins.
  24. m := make(map[string]bool)
  25. for _, v := range origins {
  26. if v != "*" {
  27. if _, err := url.Parse(v); err != nil {
  28. return nil, fmt.Errorf("Invalid CORS origin: %s", err)
  29. }
  30. }
  31. m[v] = true
  32. }
  33. return &corsInfo{m}, nil
  34. }
  35. // OriginAllowed determines whether the server will allow a given CORS origin.
  36. func (c *corsInfo) OriginAllowed(origin string) bool {
  37. return c.origins["*"] || c.origins[origin]
  38. }
  39. type corsHTTPMiddleware struct {
  40. next http.Handler
  41. info *corsInfo
  42. }
  43. // addHeader adds the correct cors headers given an origin
  44. func (h *corsHTTPMiddleware) 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 *corsHTTPMiddleware) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  51. // Write CORS header.
  52. if h.info.OriginAllowed("*") {
  53. h.addHeader(w, "*")
  54. } else if origin := req.Header.Get("Origin"); h.info.OriginAllowed(origin) {
  55. h.addHeader(w, origin)
  56. }
  57. if req.Method == "OPTIONS" {
  58. w.WriteHeader(http.StatusOK)
  59. return
  60. }
  61. h.next.ServeHTTP(w, req)
  62. }