79 lines
1.3 KiB
Go
79 lines
1.3 KiB
Go
package reader
|
|
|
|
// DISCLAIMER
|
|
// ----------
|
|
// Some of the content of this file is inspired or copied from
|
|
// the golang standard library
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
// Maximum line length
|
|
const maxLineLength = 4096
|
|
|
|
// ChunkReader struct
|
|
type ChunkReader struct {
|
|
reader *bufio.Reader // the reader
|
|
isEnded bool // If we are done (2 consecutive CRLF)
|
|
}
|
|
|
|
// NewReader creates a new reader
|
|
func NewReader(r io.Reader) *ChunkReader {
|
|
|
|
br, ok := r.(*bufio.Reader)
|
|
if !ok {
|
|
br = bufio.NewReader(r)
|
|
}
|
|
|
|
return &ChunkReader{reader: br}
|
|
|
|
}
|
|
|
|
// Read reads a chunk, io.EOF when done
|
|
func (r *ChunkReader) Read() ([]byte, error) {
|
|
// already ended
|
|
if r.isEnded {
|
|
return nil, io.EOF
|
|
}
|
|
|
|
// read line
|
|
var line []byte
|
|
line, err := r.reader.ReadSlice('\n')
|
|
|
|
if err == io.EOF {
|
|
err = io.ErrUnexpectedEOF
|
|
}
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if len(line) > maxLineLength {
|
|
return nil, fmt.Errorf("HTTP line %d exceeded buffer size %d", len(line), maxLineLength)
|
|
}
|
|
|
|
line = trimSpaces(line)
|
|
|
|
if len(line) == 0 {
|
|
r.isEnded = true
|
|
return line, io.EOF
|
|
}
|
|
|
|
return line, nil
|
|
|
|
}
|
|
|
|
func trimSpaces(b []byte) []byte {
|
|
for len(b) > 0 && isSpaceChar(b[len(b)-1]) {
|
|
b = b[:len(b)-1]
|
|
}
|
|
return b
|
|
}
|
|
|
|
func isSpaceChar(b byte) bool {
|
|
return b == ' ' || b == '\t' || b == '\r' || b == '\n'
|
|
}
|