2014-07-02 10:48:37 -04:00
|
|
|
package broadcastwriter
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2014-07-02 15:28:08 -04:00
|
|
|
// BroadcastWriter accumulate multiple io.WriteCloser by stream.
|
2014-07-02 10:48:37 -04:00
|
|
|
type BroadcastWriter struct {
|
|
|
|
sync.Mutex
|
2015-07-09 12:00:03 -04:00
|
|
|
writers map[io.WriteCloser]struct{}
|
2014-07-02 10:48:37 -04:00
|
|
|
}
|
|
|
|
|
2015-07-09 12:00:03 -04:00
|
|
|
// AddWriter adds new io.WriteCloser.
|
|
|
|
func (w *BroadcastWriter) AddWriter(writer io.WriteCloser) {
|
2014-07-02 10:48:37 -04:00
|
|
|
w.Lock()
|
2015-07-09 12:00:03 -04:00
|
|
|
w.writers[writer] = struct{}{}
|
2014-07-02 10:48:37 -04:00
|
|
|
w.Unlock()
|
|
|
|
}
|
|
|
|
|
2014-07-02 15:28:08 -04:00
|
|
|
// Write writes bytes to all writers. Failed writers will be evicted during
|
|
|
|
// this call.
|
2014-07-02 10:48:37 -04:00
|
|
|
func (w *BroadcastWriter) Write(p []byte) (n int, err error) {
|
|
|
|
w.Lock()
|
2015-07-09 12:00:03 -04:00
|
|
|
for sw := range w.writers {
|
|
|
|
if n, err := sw.Write(p); err != nil || n != len(p) {
|
|
|
|
// On error, evict the writer
|
|
|
|
delete(w.writers, sw)
|
2015-03-30 17:30:01 -04:00
|
|
|
}
|
2014-07-02 10:48:37 -04:00
|
|
|
}
|
2014-07-02 15:28:08 -04:00
|
|
|
w.Unlock()
|
2014-07-02 10:48:37 -04:00
|
|
|
return len(p), nil
|
|
|
|
}
|
|
|
|
|
2014-07-02 15:28:08 -04:00
|
|
|
// Clean closes and removes all writers. Last non-eol-terminated part of data
|
|
|
|
// will be saved.
|
|
|
|
func (w *BroadcastWriter) Clean() error {
|
2014-07-02 10:48:37 -04:00
|
|
|
w.Lock()
|
2015-07-09 12:00:03 -04:00
|
|
|
for w := range w.writers {
|
|
|
|
w.Close()
|
2014-07-02 10:48:37 -04:00
|
|
|
}
|
2015-07-09 12:00:03 -04:00
|
|
|
w.writers = make(map[io.WriteCloser]struct{})
|
2014-07-02 15:28:08 -04:00
|
|
|
w.Unlock()
|
2014-07-02 10:48:37 -04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func New() *BroadcastWriter {
|
|
|
|
return &BroadcastWriter{
|
2015-07-09 12:00:03 -04:00
|
|
|
writers: make(map[io.WriteCloser]struct{}),
|
2014-07-02 10:48:37 -04:00
|
|
|
}
|
|
|
|
}
|