Created
October 20, 2017 17:48
-
-
Save imjasonh/3072b4b47b92c37cadc4080ac54e899f to your computer and use it in GitHub Desktop.
Example writing newline-delimited JSON to a writer (pipe) and reading from it.
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 ( | |
"encoding/json" | |
"fmt" | |
"io" | |
"log" | |
) | |
func main() { | |
type holder struct { | |
I int `json:"i"` | |
} | |
pr, pw := io.Pipe() | |
go func() { | |
for i := 0; i < 20; i++ { | |
if err := json.NewEncoder(pw).Encode(holder{i}); err != nil { | |
log.Println("ENCODE ERROR:", err) | |
_ = pw.CloseWithError(err) | |
return | |
} | |
} | |
pr.CloseWithError(pw.Close()) | |
}() | |
var h holder | |
dec := json.NewDecoder(pr) | |
for dec.More() { | |
if err := dec.Decode(&h); err != nil { | |
log.Println("DECODE ERROR:", err) | |
_ = pr.CloseWithError(err) | |
} | |
fmt.Println("decoded", h.I) | |
} | |
if err := pr.Close(); err != nil { | |
log.Println("CLOSE ERROR:", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment