Skip to content

Commit

Permalink
fix: stats prom buckets (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
nrwiersma authored May 22, 2022
1 parent d435de0 commit 65e0a96
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions http/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/hamba/logger/v2"
"github.com/hamba/logger/v2/ctx"
"github.com/hamba/statter/v2"
"github.com/hamba/statter/v2/reporter/prometheus"
"github.com/hamba/statter/v2/tags"
"github.com/hamba/timex/mono"
)
Expand Down Expand Up @@ -40,6 +41,13 @@ func Recovery(log *logger.Logger) func(http.Handler) http.Handler {

// WithStats collects statistics about HTTP requests.
func WithStats(name string, s *statter.Statter, h http.Handler) http.Handler {
prometheus.RegisterHistogram(s,
"response.size",
[]string{"handler", "code"},
[]float64{200, 500, 900, 1500, 5000, 10000},
"The size of a response in bytes",
)

return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
t := make([]statter.Tag, 1, 2)
if name == "" {
Expand Down
20 changes: 20 additions & 0 deletions http/middleware/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/hamba/logger/v2"
"github.com/hamba/pkg/v2/http/middleware"
"github.com/hamba/statter/v2"
"github.com/hamba/statter/v2/reporter/prometheus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -115,6 +116,25 @@ func TestWithStats(t *testing.T) {
}
}

func TestWithStats_Prometheus(t *testing.T) {
reporter := prometheus.New("test")
s := statter.New(reporter, time.Second)

h := middleware.WithStats("test-handler", s, http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(305)
}),
)

resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foobar", nil)

h.ServeHTTP(resp, req)

err := s.Close()
require.NoError(t, err)
}

type mockReporter struct {
mock.Mock
}
Expand Down

0 comments on commit 65e0a96

Please sign in to comment.