Skip to content

Repository files navigation

JSONStream provides helper functions to enable true JSON streaming capabilities.

How to get:

go get github.com/tada/jsonstream

Sample usage

Since jsonstream uses the github.com/tada/catch module, all error handling is baked into the support functions. If any error is encountered, it will result in a panic that is recovered in the top level functions Marshal and Unmarshal. Code using the support functions, like in the example below, is compact since no error propagation is needed.

package tst
import (
"encoding/json""io""time""github.com/tada/catch/pio""github.com/tada/jsonstream"
)
typetsstruct {
v time.Duration
}
// MarshalJSON is from the json.Marshaller interfacefunc (t*ts) MarshalJSON() ([]byte, error) {
// Dispatch to the helper functionreturnjsonstream.Marshal(t)
}
// UnmarshalJSON is from the json.Marshaller interfacefunc (t*ts) UnmarshalJSON(bs []byte) error {
// Dispatch to the helper functionreturnjsonstream.Unmarshal(t, bs)
}
// MarshalToJSON encode as json and stream result to the writerfunc (t*ts) MarshalToJSON(w io.Writer) {
pio.WriteByte('{', w)
jsonstream.WriteString("v", w)
pio.WriteByte(':', w)
pio.WriteInt(int64(t.v/time.Millisecond), w)
pio.WriteByte('}', w)
}
// UnmarshalToJSON decodes using the given decoderfunc (t*ts) UnmarshalFromJSON(js jsonstream.Decoder, firstToken json.Token) {
jsonstream.AssertDelim(firstToken, '{')
for {
s, ok:=js.ReadStringOrEnd('}')
if!ok {
break
}
ifs=="v" {
t.v=time.Duration(js.ReadInt()) *time.Millisecond
}
}
}

About

Helper functions to enable true JSON streaming capabilities.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages