Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion capture_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ func (m *Metrics) CaptureMetrics(w http.ResponseWriter, fn func(http.ResponseWri
return func(src io.Reader) (int64, error) {
n, err := next(src)

headerWritten = true
if n > 0 {
headerWritten = true
}
m.Written += n
return n, err
}
Expand Down
32 changes: 32 additions & 0 deletions capture_metrics_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package httpsnoop

import (
"errors"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"testing/iotest"
"time"
)

Expand Down Expand Up @@ -61,6 +63,33 @@ func TestCaptureMetrics(t *testing.T) {
WantWritten: 17,
WantCode: http.StatusOK,
},
{
Name: "empty reader before status",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(w, struct{ io.Reader }{strings.NewReader("")})
w.WriteHeader(http.StatusNoContent)
}),
WantCode: http.StatusNoContent,
},
{
Name: "failed reader before status",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := io.Copy(w, iotest.ErrReader(errors.New("upstream failed"))); err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
}
}),
WantCode: http.StatusBadGateway,
WantWritten: int64(len("upstream failed\n")),
},
{
Name: "nonempty reader before status",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(w, struct{ io.Reader }{strings.NewReader("body")})
w.WriteHeader(http.StatusBadGateway)
}),
WantCode: http.StatusOK,
WantWritten: 4,
},
{
Name: "string writer",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -112,6 +141,9 @@ func TestCaptureMetrics(t *testing.T) {
}
if err == nil {
defer res.Body.Close()
if res.StatusCode != test.WantCode {
t.Errorf("test %d: response status=%d want=%d", i, res.StatusCode, test.WantCode)
}
}
m := <-ch
if m.Code != test.WantCode {
Expand Down