Add CORS top level middleware router to knotserver/ #735

merged
opened by nekomimi.pet targeting master from [deleted fork]: master

To make it easier to get information about tangled repos, CORS need to be enabled on repo knots otherwise browsers will throw a fit. This change adds those headers. I think maybe the auth routes could do without them as right now it just gives it to all the routes.

Changed files
+19
knotserver
+18
knotserver/middleware.go
···
)
})
}
···
)
})
}
+
+
func (h *Knot) CORS(next http.Handler) http.Handler {
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+
// Set CORS headers
+
w.Header().Set("Access-Control-Allow-Origin", "*")
+
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
+
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
+
w.Header().Set("Access-Control-Max-Age", "86400")
+
+
// Handle preflight requests
+
if r.Method == "OPTIONS" {
+
w.WriteHeader(http.StatusOK)
+
return
+
}
+
+
next.ServeHTTP(w, r)
+
})
+
}
+1
knotserver/router.go
···
func (h *Knot) Router() http.Handler {
r := chi.NewRouter()
r.Use(h.RequestLogger)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
···
func (h *Knot) Router() http.Handler {
r := chi.NewRouter()
+
r.Use(h.CORS)
r.Use(h.RequestLogger)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {