Last active
August 28, 2015 21:38
-
-
Save liggitt/29077b2835004caab5c3 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"bytes" | |
"fmt" | |
"io" | |
"os" | |
"time" | |
) | |
func main() { | |
debug = true | |
r := NewBlockingReader("hello\n") | |
go func() { | |
fmt.Println("Starting copy") | |
io.Copy(os.Stdout, r) | |
fmt.Println("Finished copy (won't ever get here because the reader blocks)") | |
}() | |
for { | |
time.Sleep(time.Second) | |
fmt.Println("Still waiting...") | |
} | |
} | |
var debug = false | |
type BlockingBuffer struct { | |
Reader io.Reader | |
} | |
// NewBlockingReader returns a reader that allows reading the given string, then blocks (doesn't return EOF or return from final Read call) | |
func NewBlockingReader(s string) io.Reader { | |
return &BlockingBuffer{Reader: bytes.NewBufferString(s)} | |
} | |
func (b *BlockingBuffer) Read(p []byte) (int, error) { | |
n, err := b.Reader.Read(p) | |
if debug { | |
fmt.Println(n, err) | |
} | |
switch { | |
case err == io.EOF && n > 0: | |
return n, nil | |
case err == io.EOF && n == 0: | |
if debug { | |
fmt.Println("Hit EOF with no data, blocking") | |
} | |
select {} | |
default: | |
return n, err | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment