mirror of
https://github.com/halverneus/static-file-server.git
synced 2024-11-13 21:55:31 +00:00
create handler to add cors headers to response
This commit is contained in:
parent
4a5f7d1427
commit
3434133796
@ -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 {
|
||||
|
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user