github.com/damirazo/docker@v1.9.0/pkg/ioutils/writeflusher.go (about)

     1  package ioutils
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  	"sync"
     7  )
     8  
     9  // WriteFlusher wraps the Write and Flush operation.
    10  type WriteFlusher struct {
    11  	sync.Mutex
    12  	w       io.Writer
    13  	flusher http.Flusher
    14  	flushed bool
    15  }
    16  
    17  func (wf *WriteFlusher) Write(b []byte) (n int, err error) {
    18  	wf.Lock()
    19  	defer wf.Unlock()
    20  	n, err = wf.w.Write(b)
    21  	wf.flushed = true
    22  	wf.flusher.Flush()
    23  	return n, err
    24  }
    25  
    26  // Flush the stream immediately.
    27  func (wf *WriteFlusher) Flush() {
    28  	wf.Lock()
    29  	defer wf.Unlock()
    30  	wf.flushed = true
    31  	wf.flusher.Flush()
    32  }
    33  
    34  // Flushed returns the state of flushed.
    35  // If it's flushed, return true, or else it return false.
    36  func (wf *WriteFlusher) Flushed() bool {
    37  	wf.Lock()
    38  	defer wf.Unlock()
    39  	return wf.flushed
    40  }
    41  
    42  // NewWriteFlusher returns a new WriteFlusher.
    43  func NewWriteFlusher(w io.Writer) *WriteFlusher {
    44  	var flusher http.Flusher
    45  	if f, ok := w.(http.Flusher); ok {
    46  		flusher = f
    47  	} else {
    48  		flusher = &NopFlusher{}
    49  	}
    50  	return &WriteFlusher{w: w, flusher: flusher}
    51  }