Decoder Buffered Reads The Remainder
After decoding the first JSON value, Decoder.Buffered hands back everything left unread so another consumer can take over.
Code
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
)
type Envelope struct {
Kind string `json:"kind"`
ID int `json:"id"`
}
func main() {
// one buffer holds a JSON value followed by a second one
stream := []byte(`{"kind":"deploy","id":7}{"kind":"rollback","id":8}`)
dec := json.NewDecoder(bytes.NewReader(stream))
var first Envelope
if err := dec.Decode(&first); err != nil {
fmt.Println("decode:", err)
return
}
fmt.Printf("first: %+v\n", first)
// Buffered hands back every unread byte without running another Decode
rest, err := io.ReadAll(dec.Buffered())
if err != nil {
fmt.Println("read:", err)
return
}
fmt.Println("remainder:", string(rest))
}How it works
Decoder Buffered Reads The Remainder reduces to the function main.
Nothing falls through silently — 2 checkpoints test err != nil on the way through.
Applying it
The demo output is labeled (decode:, first:, read:); each label names the call that printed it.
Statements that matter
if err != nil {
fmt.Println("read:", err)
return
}
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What does Decoder Buffered Reads The Remainder print when run?
- Execute the whole file; each printed line is prefixed with a label like `decode:`, `first:`, `read:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.