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