-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
40 lines (34 loc) · 1.05 KB
/
writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Package iobus converts an io.Reader or io.Writer to a chan []byte.
package iobus
import (
"io"
)
// Writer reads from a channel and writes anything received to the Writer.
// If there is an error writing, that will be sent on the errCh, if errCh is
// not nil.
func Writer(w io.Writer, ch <-chan []byte, errCh chan<- error) {
Config{}.Writer(w, ch, errCh)
}
// NewWriter will write anything sent to the returned channel to the provided
// writer.
func NewWriter(w io.Writer) (chan<- []byte, <-chan error) {
return Config{
MakeErrCh: true,
}.NewWriter(w)
}
// NewWriter creates the channels and runs Writer in a Go routine.
func (cfg Config) NewWriter(w io.Writer) (chan<- []byte, <-chan error) {
out := make(chan []byte)
errCh := cfg.makeErrCh()
go cfg.Writer(w, out, errCh)
return out, errCh
}
// Writer reads from the channel and writes anything it receives to the writer.
func (cfg Config) Writer(w io.Writer, ch <-chan []byte, errCh chan<- error) {
for b := range ch {
_, err := w.Write(b)
if err != nil && errCh != nil {
errCh <- err
}
}
}