Skip to content

Instantly share code, notes, and snippets.

@octete
Created February 18, 2015 22:46
Show Gist options
  • Save octete/cea4474b69d99ca22957 to your computer and use it in GitHub Desktop.
Save octete/cea4474b69d99ca22957 to your computer and use it in GitHub Desktop.
Go slow reader
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"strings"
"time"
)
const beSlow = true
// slowReader is a ... well ... slow reader.
type slowReader struct{ r io.Reader }
func (r slowReader) Read(data []byte) (int, error) {
// wait for 250 ms before reading a single byte.
time.Sleep(250 * time.Millisecond)
n, err := r.r.Read(data[:1])
if n > 0 {
fmt.Printf("%s", data[:1])
}
return n, err
}
func main() {
input := `{"Name":"A"}{"Name":"B"}{"Name":"C"}{"Name":"D"}{"Name":"E"}{"Name":"F"}{"Name":"G"}{"Name":"H"}`
var p struct{ Name string }
var r io.Reader = strings.NewReader(input)
if beSlow {
r = slowReader{r}
}
dec := json.NewDecoder(r)
for {
// This will return as soon as a whole JSON object has been parsed.
if err := dec.Decode(&p); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Printf(" -> %+v\n", p)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment