summaryrefslogtreecommitdiff
path: root/service/http
diff options
context:
space:
mode:
authorDmitry Patsura <[email protected]>2019-06-20 14:45:07 +0300
committerDmitry Patsura <[email protected]>2019-06-20 14:45:07 +0300
commitcf02521e1473ea099927e8fff1f0702f2418221d (patch)
treed73a850183da21e9e321377812c08dcf28a23c47 /service/http
parent878f2d546969e522a9bf5a964f626e3b823ce9a0 (diff)
Feature(http): Add CORS headers for all requests
Diffstat (limited to 'service/http')
-rw-r--r--service/http/service.go26
1 files changed, 23 insertions, 3 deletions
diff --git a/service/http/service.go b/service/http/service.go
index 3d9f196e..527aca1b 100644
--- a/service/http/service.go
+++ b/service/http/service.go
@@ -272,7 +272,7 @@ func (s *Service) headersMiddleware(f http.HandlerFunc) http.HandlerFunc {
}
}
-func handlePreflight(w http.ResponseWriter, r *http.Request, options *CORSMiddlewareConfig) {
+func handlePreflightRequest(w http.ResponseWriter, r *http.Request, options *CORSMiddlewareConfig) {
headers := w.Header()
headers.Add("Vary", "Origin")
@@ -298,15 +298,35 @@ func handlePreflight(w http.ResponseWriter, r *http.Request, options *CORSMiddle
if options.MaxAge > 0 {
headers.Set("Access-Control-Max-Age", strconv.Itoa(options.MaxAge))
}
+
+ w.WriteHeader(http.StatusOK);
+}
+
+func addCORSHeaders(w http.ResponseWriter, r *http.Request, options *CORSMiddlewareConfig) {
+ headers := w.Header()
+
+ headers.Add("Vary", "Origin")
+
+ if options.AllowedOrigin != "" {
+ headers.Set("Access-Control-Allow-Origin", options.AllowedOrigin)
+ }
+
+ if options.AllowedHeaders != "" {
+ headers.Set("Access-Control-Allow-Headers", options.AllowedHeaders)
+ }
+
+ if options.AllowCredentials != nil {
+ headers.Set("Access-Control-Allow-Credentials", strconv.FormatBool(*options.AllowCredentials))
+ }
}
func (s *Service) corsMiddleware(f http.HandlerFunc) http.HandlerFunc {
// Define the http.HandlerFunc
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
- handlePreflight(w, r, s.cfg.Middlewares.CORS)
- w.WriteHeader(http.StatusOK);
+ handlePreflightRequest(w, r, s.cfg.Middlewares.CORS)
} else {
+ addCORSHeaders(w, r, s.cfg.Middlewares.CORS)
f(w, r)
}
}