From 0ddc487926ef30ff7031e53a17b250325ad86bd2 Mon Sep 17 00:00:00 2001 From: Balazs Nagy Date: Tue, 30 Oct 2018 15:34:12 +0100 Subject: [PATCH 1/2] show OPTIOS as allowed using MethodHandler --- method_handler.go | 2 +- method_handler_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/method_handler.go b/method_handler.go index 2ad7b46..2b191ba 100644 --- a/method_handler.go +++ b/method_handler.go @@ -70,7 +70,7 @@ func (m *MethodHandler) Handle(method string, handler http.Handler) *MethodHandl method = strings.ToUpper(strings.TrimSpace(method)) if m.methodsAllowedStr == "" { - m.methodsAllowedStr = method + m.methodsAllowedStr = "OPTIONS, " + method } else { m.methodsAllowedStr += ", " + method } diff --git a/method_handler_test.go b/method_handler_test.go index 20646e9..679e420 100644 --- a/method_handler_test.go +++ b/method_handler_test.go @@ -47,5 +47,5 @@ func TestMethodHandler(t *testing.T) { expect(t, http.MethodDelete, srv.URL+"/user/42").statusCode(http.StatusOK). bodyEq("DELETE: remove user with ID: 42\n") expect(t, http.MethodPut, srv.URL+"/user/42").statusCode(http.StatusMethodNotAllowed). - bodyEq("Method Not Allowed\n").headerEq("Allow", "GET, POST, DELETE") + bodyEq("Method Not Allowed\n").headerEq("Allow", "OPTIONS, GET, POST, DELETE") } From e5505aaf96fa572969cb0f934fc40e3610b6a51e Mon Sep 17 00:00:00 2001 From: Balazs Nagy Date: Tue, 30 Oct 2018 16:19:00 +0100 Subject: [PATCH 2/2] Respond OK to OPTIONS request --- method_handler.go | 4 +++- method_handler_test.go | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/method_handler.go b/method_handler.go index 2b191ba..6b2230a 100644 --- a/method_handler.go +++ b/method_handler.go @@ -98,5 +98,7 @@ func (m *MethodHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Allow#Examples w.Header().Set("Allow", m.methodsAllowedStr) - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + if r.Method != http.MethodOptions { + http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + } } diff --git a/method_handler_test.go b/method_handler_test.go index 679e420..df1cbcf 100644 --- a/method_handler_test.go +++ b/method_handler_test.go @@ -48,4 +48,6 @@ func TestMethodHandler(t *testing.T) { bodyEq("DELETE: remove user with ID: 42\n") expect(t, http.MethodPut, srv.URL+"/user/42").statusCode(http.StatusMethodNotAllowed). bodyEq("Method Not Allowed\n").headerEq("Allow", "OPTIONS, GET, POST, DELETE") + expect(t, http.MethodOptions, srv.URL+"/user/42").statusCode(http.StatusOK). + headerEq("Allow", "OPTIONS, GET, POST, DELETE") }