From d435de06853ea5f3c60a99e9773a81a64a5737ee Mon Sep 17 00:00:00 2001 From: Nicholas Wiersma Date: Thu, 24 Mar 2022 08:24:53 +0200 Subject: [PATCH] feat: add more convenience functions (#46) --- http/{health.go => handlers.go} | 11 ++++++++--- http/{health_test.go => handlers_test.go} | 10 ++++++++++ http/middleware/middleware.go | 14 ++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) rename http/{health.go => handlers.go} (65%) rename http/{health_test.go => handlers_test.go} (80%) diff --git a/http/health.go b/http/handlers.go similarity index 65% rename from http/health.go rename to http/handlers.go index b9861f1..1756ed7 100644 --- a/http/health.go +++ b/http/handlers.go @@ -1,8 +1,13 @@ package http -import ( - "net/http" -) +import "net/http" + +// OK replies to the request with an HTTP 200 ok reply. +func OK(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusOK) } + +// OKHandler returns a simple request handler +// that replies to each request with a ``200 OK'' reply. +func OKHandler() http.Handler { return http.HandlerFunc(OK) } // DefaultHealthPath is the default HTTP path for checking health. var DefaultHealthPath = "/health" diff --git a/http/health_test.go b/http/handlers_test.go similarity index 80% rename from http/health_test.go rename to http/handlers_test.go index 4db3196..fa320c5 100644 --- a/http/health_test.go +++ b/http/handlers_test.go @@ -10,6 +10,16 @@ import ( "github.com/stretchr/testify/assert" ) +func TestOKHandler(t *testing.T) { + h := httpx.OKHandler() + + w := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/something", nil) + h.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) +} + func TestNewHealthHandler(t *testing.T) { tests := []struct { name string diff --git a/http/middleware/middleware.go b/http/middleware/middleware.go index c2e2460..5f2858e 100644 --- a/http/middleware/middleware.go +++ b/http/middleware/middleware.go @@ -31,6 +31,13 @@ func WithRecovery(h http.Handler, log *logger.Logger) http.Handler { }) } +// Recovery is a wrapper for WithRecovery. +func Recovery(log *logger.Logger) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return WithRecovery(next, log) + } +} + // WithStats collects statistics about HTTP requests. func WithStats(name string, s *statter.Statter, h http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { @@ -55,6 +62,13 @@ func WithStats(name string, s *statter.Statter, h http.Handler) http.Handler { }) } +// Stats is a wrapper for WithStats. +func Stats(name string, s *statter.Statter) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return WithStats(name, s, next) + } +} + type responseWrapper struct { http.ResponseWriter