2015-09-13 14:01:50 -04:00
|
|
|
package net
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2015-09-22 07:25:17 -04:00
|
|
|
bufferSize = 4 * 1024
|
2015-09-13 14:01:50 -04:00
|
|
|
)
|
|
|
|
|
2015-10-03 15:42:03 -04:00
|
|
|
func ReadFrom(reader io.Reader) ([]byte, error) {
|
|
|
|
buffer := make([]byte, bufferSize)
|
|
|
|
nBytes, err := reader.Read(buffer)
|
|
|
|
return buffer[:nBytes], err
|
|
|
|
}
|
|
|
|
|
2015-09-21 06:15:25 -04:00
|
|
|
// ReaderToChan dumps all content from a given reader to a chan by constantly reading it until EOF.
|
2015-09-13 14:01:50 -04:00
|
|
|
func ReaderToChan(stream chan<- []byte, reader io.Reader) error {
|
|
|
|
for {
|
2015-10-03 15:42:03 -04:00
|
|
|
data, err := ReadFrom(reader)
|
|
|
|
if len(data) > 0 {
|
|
|
|
stream <- data
|
2015-09-14 12:19:17 -04:00
|
|
|
}
|
2015-09-13 14:01:50 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-09-21 06:15:25 -04:00
|
|
|
// ChanToWriter dumps all content from a given chan to a writer until the chan is closed.
|
2015-09-13 14:01:50 -04:00
|
|
|
func ChanToWriter(writer io.Writer, stream <-chan []byte) error {
|
|
|
|
for buffer := range stream {
|
2015-09-13 18:30:50 -04:00
|
|
|
_, err := writer.Write(buffer)
|
2015-09-13 14:01:50 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|