Source File
jsonlazy.go
Belonging Package
go.pact.im/x/jsonlazy
// Package jsonlazy implements delayed JSON encoding for values that do not
// implement json.Marshaler interface.
package jsonlazy
import (
)
var (
_ json.Marshaler = (*Marshaler)(nil)
_ json.Marshaler = (*OnceMarshaler)(nil)
)
// Marshaler implements a delayed JSON encoding for values.
type Marshaler struct {
v interface{}
}
// NewMarshaler returns a new Marshaler for the given value.
func ( interface{}) *Marshaler {
return &Marshaler{}
}
// MarshalJSON implemnets the json.Marshaler interface.
func ( *Marshaler) () ([]byte, error) {
return json.Marshal(.v)
}
// Once is a shorthand for jsonlazy.Once(m).
func ( *Marshaler) () *OnceMarshaler {
return Once()
}
// OnceMarshaler is a json.Marshaler that caches the result of MarshalJSON call.
type OnceMarshaler struct {
m json.Marshaler
once sync.Once
data []byte
err error
}
// Once returns a new marshaler that caches the result of MarshalJSON call. That
// is, it calls MarshalJSON at most once.
func ( json.Marshaler) *OnceMarshaler {
return &OnceMarshaler{
m: ,
}
}
// MarshalJSON implements the json.Marshaler interface.
func ( *OnceMarshaler) () ([]byte, error) {
.once.Do(func() {
.data, .err = .m.MarshalJSON()
})
return .data, .err
}
The pages are generated with Golds v0.4.9. (GOOS=linux GOARCH=amd64)