-
Notifications
You must be signed in to change notification settings - Fork 5
/
example_test.go
75 lines (69 loc) · 1.43 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package ndjson_test
import (
"fmt"
"os"
"strings"
"github.com/olivere/ndjson"
)
type Location struct {
City string `json:"city"`
}
func ExampleReader() {
r := ndjson.NewReader(strings.NewReader(`{"city":"Munich"}
{"city":"Berlin"}
{"city":"London"}`))
for r.Next() {
var loc Location
if err := r.Decode(&loc); err != nil {
fmt.Fprintf(os.Stderr, "Decode failed: %v", err)
return
}
fmt.Println(loc.City)
}
if err := r.Err(); err != nil {
fmt.Fprintf(os.Stderr, "Reader failed: %v", err)
return
}
// Output:
// Munich
// Berlin
// London
}
func ExampleReader_Bytes() {
r := ndjson.NewReader(strings.NewReader(`{"city":"Munich"}
{"city":"Invalid"
{"city":"London"}`))
for r.Next() {
var loc Location
if err := r.Decode(&loc); err != nil {
fmt.Printf("Decode failed: %v. Last read: %s\n", err, string(r.Bytes()))
return
}
fmt.Println(loc.City)
}
if err := r.Err(); err != nil {
fmt.Fprintf(os.Stderr, "Reader failed: %v", err)
return
}
// Output:
// Munich
// Decode failed: unexpected end of JSON input. Last read: {"city":"Invalid"
}
func ExampleWriter() {
locations := []Location{
{City: "Munich"},
{City: "Berlin"},
{City: "London"},
}
r := ndjson.NewWriter(os.Stdout)
for _, loc := range locations {
if err := r.Encode(loc); err != nil {
fmt.Fprintf(os.Stderr, "Encode failed: %v", err)
return
}
}
// Output:
// {"city":"Munich"}
// {"city":"Berlin"}
// {"city":"London"}
}