2015-04-04 19:06:41 +00:00
|
|
|
package gatedwriter
|
|
|
|
|
|
|
|
import (
|
2020-01-23 18:57:18 +00:00
|
|
|
"bytes"
|
2015-04-04 19:06:41 +00:00
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Writer is an io.Writer implementation that buffers all of its
|
|
|
|
// data into an internal buffer until it is told to let data through.
|
|
|
|
type Writer struct {
|
2020-01-23 18:57:18 +00:00
|
|
|
writer io.Writer
|
2015-04-04 19:06:41 +00:00
|
|
|
|
2020-01-23 18:57:18 +00:00
|
|
|
buf bytes.Buffer
|
2015-04-04 19:06:41 +00:00
|
|
|
flush bool
|
2020-01-23 18:57:18 +00:00
|
|
|
lock sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWriter(underlying io.Writer) *Writer {
|
|
|
|
return &Writer{writer: underlying}
|
2015-04-04 19:06:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Flush tells the Writer to flush any buffered data and to stop
|
|
|
|
// buffering.
|
2020-01-23 19:24:13 +00:00
|
|
|
func (w *Writer) Flush() error {
|
2015-04-04 19:06:41 +00:00
|
|
|
w.lock.Lock()
|
2020-01-23 18:57:18 +00:00
|
|
|
defer w.lock.Unlock()
|
2015-04-04 19:06:41 +00:00
|
|
|
|
2020-01-23 18:57:18 +00:00
|
|
|
w.flush = true
|
2020-01-23 19:24:13 +00:00
|
|
|
_, err := w.buf.WriteTo(w.writer)
|
|
|
|
return err
|
2015-04-04 19:06:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (w *Writer) Write(p []byte) (n int, err error) {
|
2020-01-23 18:57:18 +00:00
|
|
|
w.lock.Lock()
|
|
|
|
defer w.lock.Unlock()
|
2015-04-04 19:06:41 +00:00
|
|
|
|
|
|
|
if w.flush {
|
2020-01-23 18:57:18 +00:00
|
|
|
return w.writer.Write(p)
|
2015-04-04 19:06:41 +00:00
|
|
|
}
|
|
|
|
|
2020-01-23 18:57:18 +00:00
|
|
|
return w.buf.Write(p)
|
2015-04-04 19:06:41 +00:00
|
|
|
}
|