Skip to content

Commit 2629f7b

Browse files
strahervagg
authored andcommitted
Add CORS middleware to web server (#629)
1 parent 3e0e06e commit 2629f7b

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

web/srv.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ var webDev = os.Getenv("CURIO_WEB_DEV") == "1"
4141

4242
func GetSrv(ctx context.Context, deps *deps.Deps, devMode bool) (*http.Server, error) {
4343
mx := mux.NewRouter()
44+
mx.Use(corsMiddleware)
45+
4446
if !devMode {
4547
api.Routes(mx.PathPrefix("/api").Subrouter(), deps, webDev)
4648
} else {
@@ -276,3 +278,19 @@ func proxyCopy(dst, src *websocket.Conn, errc chan<- error, direction string) {
276278
}
277279
}
278280
}
281+
282+
func corsMiddleware(next http.Handler) http.Handler {
283+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
284+
w.Header().Set("Access-Control-Allow-Origin", "*")
285+
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
286+
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
287+
w.Header().Set("Access-Control-Allow-Credentials", "true")
288+
289+
if r.Method == http.MethodOptions {
290+
w.WriteHeader(http.StatusOK)
291+
return
292+
}
293+
294+
next.ServeHTTP(w, r)
295+
})
296+
}

0 commit comments

Comments
 (0)