From 3177f30829439604315563b32ace6f1305b43a66 Mon Sep 17 00:00:00 2001 From: Elias Nahum Date: Tue, 1 Mar 2016 22:12:05 -0300 Subject: Add Cors Handler --- api/context.go | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'api/context.go') diff --git a/api/context.go b/api/context.go index 91b11670b..918ba3557 100644 --- a/api/context.go +++ b/api/context.go @@ -238,6 +238,47 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } +func (cw *CorsWrapper) ServeHTTP( + w http.ResponseWriter, + r *http.Request) { + allowedMethods := []string{ + "POST", + "GET", + "OPTIONS", + "PUT", + "PATCH", + "DELETE", + } + + allowedHeaders := []string{ + "Accept", + "Content-Type", + "Content-Length", + "Accept-Encoding", + "Authorization", + "X-CSRF-Token", + "X-Auth-Token", + } + + if len(*utils.Cfg.ServiceSettings.AllowCorsFrom) > 0 { + w.Header().Set("Access-Control-Allow-Origin", *utils.Cfg.ServiceSettings.AllowCorsFrom) + + w.Header().Set( + "Access-Control-Allow-Methods", + strings.Join(allowedMethods, ", ")) + + w.Header().Set( + "Access-Control-Allow-Headers", + strings.Join(allowedHeaders, ", ")) + } + + if r.Method == "OPTIONS" { + return + } + + cw.router.ServeHTTP(w, r) +} + func GetProtocol(r *http.Request) string { if r.Header.Get(model.HEADER_FORWARDED_PROTO) == "https" { return "https" -- cgit v1.2.3-1-g7c22