Skip to content

Instantly share code, notes, and snippets.

@liggitt
Last active August 28, 2015 21:38
Show Gist options
  • Save liggitt/29077b2835004caab5c3 to your computer and use it in GitHub Desktop.
Save liggitt/29077b2835004caab5c3 to your computer and use it in GitHub Desktop.
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