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

@@ -13,6 +13,20 @@ type WithCodeResponseWriter struct {
Code int
}
// NewWithCodeResponseWriter returns a WithCodeResponseWriter.
// If writer is already a WithCodeResponseWriter, it returns writer directly.
func NewWithCodeResponseWriter(writer http.ResponseWriter) *WithCodeResponseWriter {
switch w := writer.(type) {
case *WithCodeResponseWriter:
return w
default:
return &WithCodeResponseWriter{
Writer: writer,
Code: http.StatusOK,
}
}
}
// Flush flushes the response writer.
func (w *WithCodeResponseWriter) Flush() {
if flusher, ok := w.Writer.(http.Flusher); ok {

View File

@@ -11,7 +11,7 @@ import (
func TestWithCodeResponseWriter(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cw := &WithCodeResponseWriter{Writer: w}
cw := NewWithCodeResponseWriter(w)
cw.Header().Set("X-Test", "test")
cw.WriteHeader(http.StatusServiceUnavailable)
@@ -34,9 +34,7 @@ func TestWithCodeResponseWriter(t *testing.T) {
func TestWithCodeResponseWriter_Hijack(t *testing.T) {
resp := httptest.NewRecorder()
writer := &WithCodeResponseWriter{
Writer: resp,
}
writer := NewWithCodeResponseWriter(NewWithCodeResponseWriter(resp))
assert.NotPanics(t, func() {
writer.Hijack()
})