chore: avoid nested WithCodeResponseWriter (#3406)

This commit is contained in:
Kevin Wan
2023-07-11 23:59:43 +08:00
committed by GitHub
parent e8c1e6e09b
commit 13cdbdc98b
10 changed files with 81 additions and 39 deletions

View File

@@ -2,6 +2,7 @@ package handler
import (
"bytes"
"errors"
"io"
"net/http"
"net/http/httptest"
@@ -88,18 +89,23 @@ func TestLogHandlerSlow(t *testing.T) {
func TestDetailedLogHandler_Hijack(t *testing.T) {
resp := httptest.NewRecorder()
writer := &detailLoggedResponseWriter{
writer: &response.WithCodeResponseWriter{
Writer: resp,
},
writer: response.NewWithCodeResponseWriter(resp),
}
assert.NotPanics(t, func() {
_, _, _ = writer.Hijack()
})
writer = &detailLoggedResponseWriter{
writer: &response.WithCodeResponseWriter{
Writer: mockedHijackable{resp},
},
writer: response.NewWithCodeResponseWriter(resp),
}
assert.NotPanics(t, func() {
_, _, _ = writer.Hijack()
})
writer = &detailLoggedResponseWriter{
writer: response.NewWithCodeResponseWriter(mockedHijackable{
ResponseRecorder: resp,
}),
}
assert.NotPanics(t, func() {
_, _, _ = writer.Hijack()
@@ -133,6 +139,13 @@ func TestWrapStatusCodeWithColor(t *testing.T) {
assert.Equal(t, "503", wrapStatusCode(http.StatusServiceUnavailable))
}
func TestDumpRequest(t *testing.T) {
const errMsg = "error"
r := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody)
r.Body = mockedReadCloser{errMsg: errMsg}
assert.Equal(t, errMsg, dumpRequest(r))
}
func BenchmarkLogHandler(b *testing.B) {
b.ReportAllocs()
@@ -146,3 +159,15 @@ func BenchmarkLogHandler(b *testing.B) {
handler.ServeHTTP(resp, req)
}
}
type mockedReadCloser struct {
errMsg string
}
func (m mockedReadCloser) Read(p []byte) (n int, err error) {
return 0, errors.New(m.errMsg)
}
func (m mockedReadCloser) Close() error {
return nil
}