Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

79 rindas
2.3 KiB

  1. // Copyright 2015 Google Inc. All rights reserved.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package cors provides CORS support for http.Handlers.
  15. package cors
  16. import (
  17. "net/http"
  18. )
  19. // Handler is an http.Handler that wraps other http.Handlers and provides CORS
  20. // support.
  21. type Handler struct {
  22. handler http.Handler
  23. origin string
  24. allowCredentials bool
  25. }
  26. // NewHandler wraps an existing http.Handler allowing it to be requested via CORS.
  27. func NewHandler(h http.Handler) *Handler {
  28. return &Handler{
  29. handler: h,
  30. origin: "*",
  31. }
  32. }
  33. // SetOrigin sets the origin(s) to allow when requested with CORS.
  34. func (h *Handler) SetOrigin(origin string) {
  35. h.origin = origin
  36. }
  37. // AllowCredentials allows cookies to be read by the CORS request.
  38. func (h *Handler) AllowCredentials(allow bool) {
  39. h.allowCredentials = allow
  40. }
  41. // ServeHTTP determines if a request is a CORS request (normal or preflight)
  42. // and sets the appropriate Access-Control-Allow-* headers. It will send the
  43. // request to the underlying handler in all cases, except for a preflight
  44. // (OPTIONS) request.
  45. func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  46. // Definitely not a CORS request, send it directly to handler.
  47. if req.Header.Get("Origin") == "" {
  48. h.handler.ServeHTTP(rw, req)
  49. return
  50. }
  51. rw.Header().Set("Access-Control-Allow-Origin", h.origin)
  52. if h.allowCredentials {
  53. rw.Header().Set("Access-Control-Allow-Credentials", "true")
  54. }
  55. acrm := req.Header.Get("Access-Control-Request-Method")
  56. rw.Header().Set("Access-Control-Allow-Methods", acrm)
  57. if acrh := req.Header.Get("Access-Control-Request-Headers"); acrh != "" {
  58. rw.Header().Set("Access-Control-Allow-Headers", acrh)
  59. }
  60. // Preflight request, don't bother sending it to the handler.
  61. if req.Method == "OPTIONS" {
  62. return
  63. }
  64. h.handler.ServeHTTP(rw, req)
  65. }