From a50705d3d6dd0b17a9ee37b25c60c14e50df2329 Mon Sep 17 00:00:00 2001 From: Tianon Gravi Date: Fri, 8 May 2015 12:33:33 -0600 Subject: [PATCH] Move WriteFlusher out of utils into ioutils Signed-off-by: Andrew "Tianon" Page --- ioutils/writeflusher.go | 47 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 ioutils/writeflusher.go diff --git a/ioutils/writeflusher.go b/ioutils/writeflusher.go new file mode 100644 index 0000000..2509547 --- /dev/null +++ b/ioutils/writeflusher.go @@ -0,0 +1,47 @@ +package ioutils + +import ( + "io" + "net/http" + "sync" +) + +type WriteFlusher struct { + sync.Mutex + w io.Writer + flusher http.Flusher + flushed bool +} + +func (wf *WriteFlusher) Write(b []byte) (n int, err error) { + wf.Lock() + defer wf.Unlock() + n, err = wf.w.Write(b) + wf.flushed = true + wf.flusher.Flush() + return n, err +} + +// Flush the stream immediately. +func (wf *WriteFlusher) Flush() { + wf.Lock() + defer wf.Unlock() + wf.flushed = true + wf.flusher.Flush() +} + +func (wf *WriteFlusher) Flushed() bool { + wf.Lock() + defer wf.Unlock() + return wf.flushed +} + +func NewWriteFlusher(w io.Writer) *WriteFlusher { + var flusher http.Flusher + if f, ok := w.(http.Flusher); ok { + flusher = f + } else { + flusher = &NopFlusher{} + } + return &WriteFlusher{w: w, flusher: flusher} +}