From 3434133796be03563c300c479ffdf3c0e7f9a796 Mon Sep 17 00:00:00 2001 From: "Demi [Alvaro Martinez de Miguel]" Date: Tue, 15 Oct 2019 20:06:56 +0200 Subject: [PATCH] create handler to add cors headers to response --- handle/handle.go | 9 +++++++++ handle/handle_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/handle/handle.go b/handle/handle.go index babedd3..f0d3e91 100644 --- a/handle/handle.go +++ b/handle/handle.go @@ -109,6 +109,15 @@ func IgnoreIndex(serve http.HandlerFunc) http.HandlerFunc { } } +func AddCorsHeaders(serve http.HandlerFunc) http.HandlerFunc { + return func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Access-Control-Allow-Origin", "*") + writer.Header().Set("Access-Control-Allow-Headers", "*") + + serve(writer, request) + } +} + // Listening function for serving the handler function. func Listening() ListenerFunc { return func(binding string, handler http.HandlerFunc) error { diff --git a/handle/handle_test.go b/handle/handle_test.go index 11dd6d7..2ad5eb4 100644 --- a/handle/handle_test.go +++ b/handle/handle_test.go @@ -9,6 +9,7 @@ import ( "os" "path" "testing" + "strings" ) var ( @@ -458,3 +459,32 @@ func TestValidReferrer(t *testing.T) { }) } } + +func TestAddsCorsHeaders(t *testing.T) { + testCases := []struct { + name string + header string + value string + }{ + {"Add Access-Control-Allow-Origin header", "Access-Control-Allow-Origin", "*"}, + {"Add Access-Control-Allow-Headers header", "Access-Control-Allow-Headers", "*"}, + } + + for _, serveFile := range serveFileFuncs { + handler := AddCorsHeaders(Basic(serveFile, baseDir)) + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + req := httptest.NewRequest("GET", "http://localhost/", nil) + w := httptest.NewRecorder() + + handler(w, req) + + resp := w.Result() + headerValue := strings.Join(resp.Header[tc.header], ", ") + if headerValue != tc.value { + t.Errorf("Response header %q = %q, want %q", tc.header, headerValue, tc.value) + } + }) + } + } +}