Skip to content

Commit

Permalink
Open access to the underlying byte slice
Browse files Browse the repository at this point in the history
This commit opens up access to the byte slice of the underlying
`bufio.Scanner`. It can be used to get access to the most recent error
when e.g. a line cannot be parsed correctly. See the code in
`ExampleReader_Bytes` for an example.
  • Loading branch information
olivere committed Sep 22, 2021
1 parent 54f8da2 commit 5e76790
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions CONTRIBUTORS
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
edhaight [@edhaight](https://github.com/edhaight)
Manuel Laflamme [@mlaflamm](https://github.com/mlaflamm)
21 changes: 21 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,27 @@ func ExampleReader() {
// 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"},
Expand Down
7 changes: 7 additions & 0 deletions reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ func (r *Reader) Next() bool {
return r.s.Scan()
}

// Bytes returns the most recent buffer generated by a call to Next.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Next. It does no allocation.
func (r *Reader) Bytes() []byte {
return r.s.Bytes()
}

// Err returns the first non-EOF error that was encountered by the Reader.
func (r *Reader) Err() error {
return r.s.Err()
Expand Down

0 comments on commit 5e76790

Please sign in to comment.