From ca00fc8159ee7956c2a5d71142cff0133e56f698 Mon Sep 17 00:00:00 2001 From: Nate Meyer <672246+notnmeyer@users.noreply.github.com> Date: Tue, 9 Jan 2024 18:24:39 -0800 Subject: [PATCH] feat: respond to preflight requests (#16) --- main.go | 20 +++++++++++++++----- main_test.go | 20 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 90ba69f..a1f70e8 100644 --- a/main.go +++ b/main.go @@ -32,11 +32,21 @@ func main() { } func handler(w http.ResponseWriter, r *http.Request) { - responseBody, responseCode := buildResponse(r.Header) - - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(responseCode) - w.Write([]byte(responseBody)) + switch r.Method { + case "OPTIONS": + w.Header().Set("Connection", "keep-alive") + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "*") + w.Header().Set("Access-Control-Allow-Headers", "*") + w.Header().Set("Access-Control-Max-Age", "86400") + w.WriteHeader(http.StatusNoContent) + default: + responseBody, responseCode := buildResponse(r.Header) + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Access-Control-Allow-Origin", "*") + w.WriteHeader(responseCode) + w.Write([]byte(responseBody)) + } } func buildResponse(header map[string][]string) (string, int) { diff --git a/main_test.go b/main_test.go index 236422d..998563e 100644 --- a/main_test.go +++ b/main_test.go @@ -125,6 +125,26 @@ func TestHandlerWithInvalidXResponseCode(t *testing.T) { } } +func TestHandlerPreflightRequest(t *testing.T) { + expectedResponseCode := http.StatusNoContent + + // set up the request + req, err := http.NewRequest("OPTIONS", "/test", nil) + if err != nil { + t.Fatal(err) + } + + // make the request + rr := httptest.NewRecorder() + h := http.HandlerFunc(handler) + h.ServeHTTP(rr, req) + + // status code + if status := rr.Code; status != expectedResponseCode { + t.Errorf("handler returned wrong status code: got '%d' want '%d'", status, expectedResponseCode) + } +} + func TestValidateResponseCode(t *testing.T) { valid := map[string][]string{ "X-Response-Code": {"201"},