From 44b40e45b451a38b6872bd0d81d6c5bd82fc2834 Mon Sep 17 00:00:00 2001 From: xieyuschen Date: Wed, 7 Aug 2024 21:59:36 +0800 Subject: [PATCH] refine: return error instead of panic when response writer doesn't implement hijacker --- response_writer.go | 7 ++++++- response_writer_test.go | 6 ++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/response_writer.go b/response_writer.go index 753a0b09ab..e1d3da0500 100644 --- a/response_writer.go +++ b/response_writer.go @@ -6,6 +6,7 @@ package gin import ( "bufio" + "errors" "io" "net" "net/http" @@ -109,7 +110,11 @@ func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if w.size < 0 { w.size = 0 } - return w.ResponseWriter.(http.Hijacker).Hijack() + hijacker, ok := w.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, errors.New("response writer does not support Hijack") + } + return hijacker.Hijack() } // CloseNotify implements the http.CloseNotifier interface. diff --git a/response_writer_test.go b/response_writer_test.go index 259b8fa820..92e77b85bb 100644 --- a/response_writer_test.go +++ b/response_writer_test.go @@ -111,10 +111,8 @@ func TestResponseWriterHijack(t *testing.T) { writer.reset(testWriter) w := ResponseWriter(writer) - assert.Panics(t, func() { - _, _, err := w.Hijack() - require.NoError(t, err) - }) + _, _, err := w.Hijack() + assert.Equal(t, "response writer does not support Hijack", err.Error()) assert.True(t, w.Written()) assert.Panics(t, func() {