add chunk reader for websocket

This commit is contained in:
xdrm-brackets 2018-04-27 08:48:19 +02:00
parent 2bb8b81a21
commit b1d0a71dd5
1 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,52 @@
package reader
import (
"io"
"bufio"
)
// Chunk reader
type chunkReader struct {
reader *bufio.Reader // the reader
}
// New creates a new reader
func NewReader(r io.Reader) (reader *chunkReader) {
br, ok := r.(*bufio.Reader)
if !ok {
br = bufio.NewReader(r)
}
return &chunkReader{reader: br}
}
// Read reads a chunk of n bytes
// err is io.EOF when done
func (r *chunkReader) Read(n uint) ([]byte, error){
/* (1) Read line */
chunk := make([]byte, n)
read, err := r.reader.Read(chunk)
/* (2) manage errors */
if err == io.EOF {
err = io.EOF
}
if err != nil {
return chunk, err
}
/* (1) Manage ending chunk */
if uint(read) == 0 || len(chunk) == 0 {
return chunk, io.EOF
}
return chunk, nil
}