Skip to content

Commit

Permalink
added check to prevent HasContent() to panic after the reader is
Browse files Browse the repository at this point in the history
closed

* fixes #268

Signed-off-by: Frederic BIDON <[email protected]>
  • Loading branch information
fredbi committed Dec 8, 2023
1 parent 337c930 commit 1af6e90
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package runtime

import (
"bufio"
"errors"
"io"
"net/http"
"strings"
Expand Down Expand Up @@ -96,10 +97,16 @@ func (p *peekingReader) Read(d []byte) (int, error) {
if p == nil {
return 0, io.EOF
}
if p.underlying == nil {
return 0, io.ErrUnexpectedEOF
}
return p.underlying.Read(d)
}

func (p *peekingReader) Close() error {
if p.underlying == nil {
return errors.New("reader already closed")
}
p.underlying = nil
if p.orig != nil {
return p.orig.Close()
Expand Down
33 changes: 33 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,39 @@ func TestPeekingReader(t *testing.T) {
require.Equal(t, 1, cbr.peeks)
require.Equal(t, 2, cbr.reads)
require.Equal(t, 0, cbr.br.Buffered())

t.Run("closing a closed peekingReader", func(t *testing.T) {
const content = "content"
r := newPeekingReader(io.NopCloser(strings.NewReader(content)))
require.NoError(t, r.Close())

require.NotPanics(t, func() {
err := r.Close()
require.Error(t, err)
})
})

t.Run("reading from a closed peekingReader", func(t *testing.T) {
const content = "content"
r := newPeekingReader(io.NopCloser(strings.NewReader(content)))
require.NoError(t, r.Close())

require.NotPanics(t, func() {
_, err := io.ReadAll(r)
require.Error(t, err)
require.ErrorIs(t, err, io.ErrUnexpectedEOF)
})
})

t.Run("reading from a nil peekingReader", func(t *testing.T) {
var r *peekingReader
require.NotPanics(t, func() {
buf := make([]byte, 10)
_, err := r.Read(buf)
require.Error(t, err)
require.ErrorIs(t, err, io.EOF)
})
})
}

func TestJSONRequest(t *testing.T) {
Expand Down

0 comments on commit 1af6e90

Please sign in to comment.