Skip to content

Commit 4b918bb

Browse files
committed
Refactor & enhance CORS support
Only sends allow method/headers headers for `OPTIONS` requests. Uses the value of `Origin` for the allow origin header if it is available. If an origin is set then it allows credentials. Fixes #29.
1 parent eab2821 commit 4b918bb

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

apisprout.go

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -370,11 +370,33 @@ func server(cmd *cobra.Command, args []string) {
370370
// the appropriate OpenAPI operation and try to return an example.
371371
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
372372
if !viper.GetBool("disable-cors") {
373+
corsOrigin := req.Header.Get("Origin")
374+
if corsOrigin == "" {
375+
corsOrigin = "*"
376+
}
377+
w.Header().Set("Access-Control-Allow-Origin", corsOrigin)
378+
379+
if corsOrigin != "*" {
380+
// Allow credentials to be sent if an origin has been specified.
381+
// This is done *outside* of an OPTIONS request since it might be
382+
// required for a non-preflighted GET/POST request.
383+
w.Header().Set("Access-Control-Allow-Credentials", "true")
384+
}
385+
373386
// Handle pre-flight OPTIONS request
374387
if (*req).Method == "OPTIONS" {
375-
w.Header().Set("Access-Control-Allow-Origin", "*")
376-
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
377-
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
388+
corsMethod := req.Header.Get("Access-Control-Request-Method")
389+
if corsMethod == "" {
390+
corsMethod = "POST, GET, OPTIONS, PUT, DELETE"
391+
}
392+
393+
corsHeaders := req.Header.Get("Access-Control-Request-Headers")
394+
if corsHeaders == "" {
395+
corsHeaders = "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"
396+
}
397+
398+
w.Header().Set("Access-Control-Allow-Methods", corsMethod)
399+
w.Header().Set("Access-Control-Allow-Headers", corsHeaders)
378400
return
379401
}
380402
}
@@ -471,13 +493,6 @@ func server(cmd *cobra.Command, args []string) {
471493
w.Header().Add("Content-Type", mediatype)
472494
}
473495

474-
if !viper.GetBool("disable-cors") {
475-
// Add CORS headers to allow all origins and methods.
476-
w.Header().Set("Access-Control-Allow-Origin", "*")
477-
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
478-
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
479-
}
480-
481496
w.WriteHeader(status)
482497
w.Write(encoded)
483498
})

0 commit comments

Comments
 (0)