Created
February 28, 2018 02:46
-
-
Save jessejlt/38011cc8f2f2046fe70f4efe3ada5e79 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"log" | |
) | |
func main() { | |
w := sink() | |
for i := 0; i < 10; i++ { | |
if _, err := w.Write(make([]byte, 1011)); err != nil { | |
log.Printf("Failed to write: %v\n", err) | |
} | |
} | |
if err := w.Close(); err != nil { | |
log.Printf("Failed to close sink: %v\n", err) | |
} | |
} | |
func sink() io.WriteCloser { | |
r, w := io.Pipe() | |
c := make(chan struct{}) | |
go func() { | |
defer close(c) | |
buf := make([]byte, 1024) | |
for { | |
_, err := r.Read(buf) | |
if err != nil { | |
if err == io.EOF { | |
log.Println("Writer Complete") | |
return | |
} | |
log.Printf("Writer abated with %v\n", err) | |
if err := w.CloseWithError(err); err != nil { | |
log.Printf("Failed to close writer: %v\n", err) | |
} | |
return | |
} | |
} | |
}() | |
return &syncWriteCloser{w: w, c: c} | |
} | |
type syncWriteCloser struct { | |
w io.WriteCloser | |
c chan struct{} | |
} | |
func (w *syncWriteCloser) Write(data []byte) (n int, err error) { | |
n, err = w.w.Write(data) | |
return | |
} | |
func (w *syncWriteCloser) Close() error { | |
err := w.w.Close() | |
for range w.c { | |
} | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment