Skip to content

Commit

Permalink
Remove mutex and add test for ReaderFrom
Browse files Browse the repository at this point in the history
Resolves felixge#13
  • Loading branch information
ebati committed Mar 18, 2021
1 parent 80c3c21 commit 5a0ae82
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
11 changes: 3 additions & 8 deletions capture_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package httpsnoop
import (
"io"
"net/http"
"sync"
"time"
)

Expand Down Expand Up @@ -40,13 +39,11 @@ func CaptureMetricsFn(w http.ResponseWriter, fn func(http.ResponseWriter)) Metri
start = time.Now()
m = Metrics{Code: http.StatusOK}
headerWritten bool
lock sync.Mutex
hooks = Hooks{
WriteHeader: func(next WriteHeaderFunc) WriteHeaderFunc {
return func(code int) {
next(code)
lock.Lock()
defer lock.Unlock()

if !headerWritten {
m.Code = code
headerWritten = true
Expand All @@ -57,8 +54,7 @@ func CaptureMetricsFn(w http.ResponseWriter, fn func(http.ResponseWriter)) Metri
Write: func(next WriteFunc) WriteFunc {
return func(p []byte) (int, error) {
n, err := next(p)
lock.Lock()
defer lock.Unlock()

m.Written += int64(n)
headerWritten = true
return n, err
Expand All @@ -68,8 +64,7 @@ func CaptureMetricsFn(w http.ResponseWriter, fn func(http.ResponseWriter)) Metri
ReadFrom: func(next ReadFromFunc) ReadFromFunc {
return func(src io.Reader) (int64, error) {
n, err := next(src)
lock.Lock()
defer lock.Unlock()

headerWritten = true
m.Written += n
return n, err
Expand Down
9 changes: 9 additions & 0 deletions capture_metrics_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package httpsnoop

import (
"io"
"io/ioutil"
"log"
"net/http"
Expand Down Expand Up @@ -48,6 +49,14 @@ func TestCaptureMetrics(t *testing.T) {
}),
WantCode: http.StatusOK,
},
{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rrf := w.(io.ReaderFrom)
rrf.ReadFrom(strings.NewReader("reader from is ok"))
}),
WantWritten: 17,
WantCode: http.StatusOK,
},
{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic("oh no")
Expand Down

0 comments on commit 5a0ae82

Please sign in to comment.