From b1d0a71dd5137975b9a3cebbf5f4578dfe2a8335 Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Fri, 27 Apr 2018 08:48:19 +0200 Subject: [PATCH] add chunk reader for websocket --- internal/ws/reader/reader.go | 52 ++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 internal/ws/reader/reader.go diff --git a/internal/ws/reader/reader.go b/internal/ws/reader/reader.go new file mode 100644 index 0000000..9e374f8 --- /dev/null +++ b/internal/ws/reader/reader.go @@ -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 + +} \ No newline at end of file