From 1fa12b4d0ca3ace40c78061f5073fe8f37288f9d Mon Sep 17 00:00:00 2001 From: Thomas le Dieu de Ville <42641097+tle-dieu@users.noreply.github.com> Date: Thu, 18 Jan 2024 10:56:20 +0100 Subject: [PATCH] Fix case of nil/http.NoBody request.Body on interceptor tripperware/middleware (#45) * no copy if src is nil on NewCopyReadCloser * Update copy_read_closer.go --- interceptor/copy_read_closer.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/interceptor/copy_read_closer.go b/interceptor/copy_read_closer.go index 5c2243d..d6abbfb 100644 --- a/interceptor/copy_read_closer.go +++ b/interceptor/copy_read_closer.go @@ -4,6 +4,7 @@ import ( "bytes" "io" "io/ioutil" + "net/http" ) // io.Reader with Read method reset offset when EOF @@ -42,7 +43,12 @@ type copyReadCloser struct { // Second read after EOF // copyBuffered --> copy BufReader simple buffer with fix size // when BufReader is EOF offset is reset to read again -func NewCopyReadCloser(src io.ReadCloser) *copyReadCloser { +func NewCopyReadCloser(src io.ReadCloser) io.ReadCloser { + // No copying needed on nil or http.NoBody. + if src == nil || src == http.NoBody { + return src + } + buf := &bytes.Buffer{} tr := ©ReadCloser{ copyTemp: buf, @@ -56,7 +62,7 @@ func NewCopyReadCloser(src io.ReadCloser) *copyReadCloser { return tr } -func (tr *copyReadCloser)Read(p []byte) (n int, err error) { +func (tr *copyReadCloser) Read(p []byte) (n int, err error) { n, err = tr.ReadCloser.Read(p) if err == io.EOF { if tr.copy == nil {