Skip to content

Commit

Permalink
feat: add more convenience functions (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
nrwiersma authored Mar 24, 2022
1 parent 90ba6f2 commit d435de0
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
11 changes: 8 additions & 3 deletions http/health.go → http/handlers.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
10 changes: 10 additions & 0 deletions http/health_test.go → http/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions http/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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

Expand Down

0 comments on commit d435de0

Please sign in to comment.