From bfb0c305b88a523cebf743b1b7daa56b072a6713 Mon Sep 17 00:00:00 2001 From: Rob Watson Date: Tue, 7 Jun 2022 05:04:33 +0200 Subject: [PATCH] Handle HEAD request --- handler/handler.go | 6 ++++-- handler/handler_test.go | 16 +++++++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/handler/handler.go b/handler/handler.go index 5dfff06..5dd78a9 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -10,7 +10,7 @@ var indexPage string func New(matrixHostname, matrixBaseURL string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet { + if r.Method != http.MethodGet && r.Method != http.MethodHead { w.WriteHeader(http.StatusMethodNotAllowed) w.Write([]byte("405 method not allowed\n")) return @@ -28,7 +28,9 @@ func New(matrixHostname, matrixBaseURL string) http.HandlerFunc { case "/": w.Header().Add("content-type", "text/html") w.WriteHeader(http.StatusOK) - w.Write([]byte(indexPage)) + if r.Method == http.MethodGet { + w.Write([]byte(indexPage)) + } default: http.NotFound(w, r) } diff --git a/handler/handler_test.go b/handler/handler_test.go index 8f7c414..e539b00 100644 --- a/handler/handler_test.go +++ b/handler/handler_test.go @@ -49,6 +49,14 @@ func TestHandler(t *testing.T) { wantStatusCode: http.StatusOK, wantBody: "Welcome to netflux.io", }, + { + name: "HEAD /", + method: http.MethodHead, + path: "/", + wantContentType: "text/html", + wantStatusCode: http.StatusOK, + wantBody: "", + }, { name: "page not found", method: http.MethodGet, @@ -81,11 +89,9 @@ func TestHandler(t *testing.T) { assert.Equal(t, tc.wantContentType, resp.Header.Get("content-type")) } - if tc.wantBody != "" { - respBody, err := ioutil.ReadAll(resp.Body) - require.NoError(t, err) - assert.Contains(t, string(respBody), tc.wantBody) - } + respBody, err := ioutil.ReadAll(resp.Body) + require.NoError(t, err) + assert.Contains(t, string(respBody), tc.wantBody) }) } }