create handler to add cors headers to response

This commit is contained in:
Demi [Alvaro Martinez de Miguel] 2019-10-15 20:06:56 +02:00
parent 4a5f7d1427
commit 3434133796
2 changed files with 39 additions and 0 deletions

View File

@ -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 {

View File

@ -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)
}
})
}
}
}