Prechádzať zdrojové kódy

Added CORS support to API.

Andras Bali 5 rokov pred
rodič
commit
adbebd4de8
2 zmenil súbory, kde vykonal 14 pridanie a 0 odobranie
  1. 2 0
      api/api.go
  2. 12 0
      api/middleware.go

+ 2 - 0
api/api.go

@@ -18,8 +18,10 @@ func Serve(router *mux.Router, store *storage.Storage, pool *worker.Pool, feedHa
 
 	sr := router.PathPrefix("/v1").Subrouter()
 	middleware := newMiddleware(store)
+	sr.Use(middleware.handleCORS)
 	sr.Use(middleware.apiKeyAuth)
 	sr.Use(middleware.basicAuth)
+	sr.Methods("OPTIONS")
 	sr.HandleFunc("/users", handler.createUser).Methods("POST")
 	sr.HandleFunc("/users", handler.users).Methods("GET")
 	sr.HandleFunc("/users/{userID:[0-9]+}", handler.userByID).Methods("GET")

+ 12 - 0
api/middleware.go

@@ -21,6 +21,18 @@ type middleware struct {
 func newMiddleware(s *storage.Storage) *middleware {
 	return &middleware{s}
 }
+func (m *middleware) handleCORS(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Access-Control-Allow-Origin", "*")
+		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS")
+		w.Header().Set("Access-Control-Allow-Headers", "X-Auth-Token")
+		if r.Method == "OPTIONS" {
+			w.WriteHeader(http.StatusOK)
+			return
+		}
+		next.ServeHTTP(w, r)
+	})
+}
 
 func (m *middleware) apiKeyAuth(next http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {