diff options
author | Luke Shumaker <lukeshu@datawire.io> | 2022-08-16 21:50:07 -0600 |
---|---|---|
committer | Luke Shumaker <lukeshu@datawire.io> | 2022-08-17 00:34:48 -0600 |
commit | 111cdaffb625f7db9b8c5a27e386999944346e0d (patch) | |
tree | cdb6493361b4343cd2cb05ef76b77cfc5a682a1b /decode.go | |
parent | 0e6d82b97165e9cdd294aaeac02bbbf26263877a (diff) |
Fix those now-failing error checks
Diffstat (limited to 'decode.go')
-rw-r--r-- | decode.go | 29 |
1 files changed, 29 insertions, 0 deletions
@@ -121,6 +121,26 @@ func Decode(r interface { return NewDecoder(r).Decode(ptr) } +// DecodeThenEOF is like decode, but emits an error if there is extra data after the JSON. +func DecodeThenEOF(r interface { + io.Reader + io.RuneScanner +}, ptr any) error { + dec := NewDecoder(r) + if err := dec.Decode(ptr); err != nil { + return err + } + if c, _, err := r.ReadRune(); err == nil { + return &DecodeError{ + Err: &DecodeSyntaxError{ + Err: fmt.Errorf("invalid character %q after top-level value", c), + Offset: dec.InputOffset(), + }, + } + } + return nil +} + func (dec *Decoder) Decode(ptr any) (err error) { ptrVal := reflect.ValueOf(ptr) if ptrVal.Kind() != reflect.Pointer || ptrVal.IsNil() || !ptrVal.Elem().CanSet() { @@ -147,6 +167,15 @@ func (dec *Decoder) Decode(ptr any) (err error) { } }() dec.decode(ptrVal.Elem(), false) + for { + _, s, t, _ := dec.io.ReadRuneType() + if t == RuneTypeEOF || t == RuneTypeError { + if s > 0 { + dec.io.UnreadRune() + } + break + } + } return nil } |