Skip to content

Commit

Permalink
fix: minor issues (#105)
Browse files Browse the repository at this point in the history
  • Loading branch information
nrwiersma authored Nov 15, 2023
1 parent 7e48d80 commit 6eaec90
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
20 changes: 17 additions & 3 deletions http/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
package middleware

import (
"bufio"
"errors"
"net"
"net/http"

"github.com/hamba/logger/v2"
Expand Down Expand Up @@ -63,7 +66,7 @@ func RequestID() func(http.Handler) http.Handler {
func WithStats(name string, s *statter.Statter, h http.Handler) http.Handler {
prometheus.RegisterHistogram(s,
"response.size",
[]string{"handler", "code"},
[]string{"handler", "code", "code-group"},
[]float64{200, 500, 900, 1500, 5000, 10000},
"The size of a response in bytes",
)
Expand All @@ -83,8 +86,8 @@ func WithStats(name string, s *statter.Statter, h http.Handler) http.Handler {
h.ServeHTTP(wrap, req)
dur := mono.Since(start)

t = append(t, tags.StatusCode("status-group", wrap.Status()))
t = append(t, tags.Int("status-code", wrap.Status()))
t = append(t, tags.StatusCode("code-group", wrap.Status()))
t = append(t, tags.Int("code", wrap.Status()))
s.Counter("responses", t...).Inc(1)
s.Histogram("response.size", t...).Observe(float64(wrap.BytesWritten()))
s.Timing("response.duration", t...).Observe(dur)
Expand Down Expand Up @@ -142,6 +145,17 @@ func (rw *responseWrapper) BytesWritten() int64 {
return rw.bytes
}

// Hijack returns a hijacked connection or an error.
//
// This is required by some websocket libraries.
func (rw *responseWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
h, ok := rw.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("hijacker not supported")
}
return h.Hijack()
}

// Unwrap returns the underlying response writer.
// This is used by http.ResponseController to find the first
// response writer that implements an interface.
Expand Down
6 changes: 5 additions & 1 deletion http/middleware/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"net/http"
"net/http/httptest"
"sort"
"testing"
"time"

Expand Down Expand Up @@ -111,7 +112,10 @@ func TestStats(t *testing.T) {

m := &mockReporter{}
m.On("Counter", "requests", int64(1), test.wantTags)
wantTags := append(test.wantTags, [][2]string{{"status-code", "305"}, {"status-group", "3xx"}}...)
wantTags := append(test.wantTags, [][2]string{{"code", "305"}, {"code-group", "3xx"}}...)
sort.Slice(wantTags, func(i, j int) bool {
return wantTags[i][0] < wantTags[j][0]
})
m.On("Counter", "responses", int64(1), wantTags)
m.On("Histogram", "response.size", wantTags).Return(func(_ float64) {})
m.On("Timing", "response.duration", wantTags).Return(func(_ time.Duration) {})
Expand Down

0 comments on commit 6eaec90

Please sign in to comment.