diff options
author | Steve Manuel <nilslice@gmail.com> | 2017-01-16 10:35:15 -0800 |
---|---|---|
committer | Steve Manuel <nilslice@gmail.com> | 2017-01-16 10:35:15 -0800 |
commit | cb4f6cd182bf538b2b7c297e56d6f7665607d19f (patch) | |
tree | 3e377c2a4d2acbfc691b5b7b8b12581b09e9b333 /system/api | |
parent | 89a43c6734a4375b4c6d5b76034020505965baac (diff) |
adding cors helper func
Diffstat (limited to 'system/api')
-rw-r--r-- | system/api/handlers.go | 27 |
1 files changed, 20 insertions, 7 deletions
diff --git a/system/api/handlers.go b/system/api/handlers.go index de7fbcb..071a373 100644 --- a/system/api/handlers.go +++ b/system/api/handlers.go @@ -234,10 +234,14 @@ func toJSON(data []string) ([]byte, error) { // sendData() should be used any time you want to communicate // data back to a foreign client func sendData(res http.ResponseWriter, data []byte, code int) { - res.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type") - res.Header().Set("Access-Control-Allow-Origin", "*") + res, cors := responseWithCORS(res) + if !cors { + return + } + res.Header().Set("Content-Type", "application/json") res.WriteHeader(code) + _, err := res.Write(data) if err != nil { log.Println("Error writing to response in sendData") @@ -252,14 +256,23 @@ func sendPreflight(res http.ResponseWriter) { return } +func responseWithCORS(res http.ResponseWriter) (http.ResponseWriter, bool) { + if db.ConfigCache("cors_disabled").(bool) == true { + // disallow request + res.WriteHeader(http.StatusForbidden) + return res, false + } + + // apply CORS headers and return + res.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type") + res.Header().Set("Access-Control-Allow-Origin", "*") + + return res, true +} + // CORS wraps a HandleFunc to respond to OPTIONS requests properly func CORS(next http.HandlerFunc) http.HandlerFunc { return db.CacheControl(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { - if db.ConfigCache("cors_disabled").(bool) == true { - res.WriteHeader(http.StatusForbidden) - return - } - if req.Method == http.MethodOptions { sendPreflight(res) return |