1package agent 2 3import ( 4 "io" 5 "sync" 6) 7 8// GatedWriter is an io.Writer implementation that buffers all of its 9// data into an internal buffer until it is told to let data through. 10type GatedWriter struct { 11 Writer io.Writer 12 13 buf [][]byte 14 flush bool 15 lock sync.RWMutex 16} 17 18var _ io.Writer = &GatedWriter{} 19 20// Flush tells the GatedWriter to flush any buffered data and to stop 21// buffering. 22func (w *GatedWriter) Flush() { 23 w.lock.Lock() 24 w.flush = true 25 w.lock.Unlock() 26 27 for _, p := range w.buf { 28 w.Write(p) 29 } 30 w.buf = nil 31} 32 33func (w *GatedWriter) Write(p []byte) (n int, err error) { 34 w.lock.RLock() 35 defer w.lock.RUnlock() 36 37 if w.flush { 38 return w.Writer.Write(p) 39 } 40 41 p2 := make([]byte, len(p)) 42 copy(p2, p) 43 w.buf = append(w.buf, p2) 44 return len(p), nil 45} 46