middleware.go 1.0 KB

1234567891011121314151617181920212223
  1. package middleware
  2. import "net/http"
  3. func Cors(handler http.Handler) http.Handler {
  4. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  5. method := r.Method
  6. origin := r.Header.Get("Origin")
  7. if origin != "" {
  8. // 允许来源配置
  9. w.Header().Set("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
  10. w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE, PATCH")
  11. w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  12. w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
  13. w.Header().Set("Access-Control-Allow-Credentials", "true")
  14. }
  15. if method == "OPTIONS" {
  16. w.WriteHeader(http.StatusNoContent)
  17. return
  18. }
  19. handler.ServeHTTP(w, r)
  20. })
  21. }