Initial import
This commit is contained in:
77
storage/codec/default.go
Normal file
77
storage/codec/default.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
|
||||
"github.com/goccy/go-yaml"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("json", func() Codec { return jsonCodec{} })
|
||||
Register("yaml", func() Codec { return yamlCodec{} })
|
||||
}
|
||||
|
||||
type jsonCodec struct{}
|
||||
|
||||
func (jsonCodec) Type() string { return "json" }
|
||||
func (jsonCodec) Encode(value any) ([]byte, error) { return json.Marshal(value) }
|
||||
func (jsonCodec) Decode(data []byte, value any) error { return json.Unmarshal(data, value) }
|
||||
|
||||
type jsonStream struct {
|
||||
decoder *json.Decoder
|
||||
encoder *json.Encoder
|
||||
}
|
||||
|
||||
type JSONOption func(*json.Encoder)
|
||||
|
||||
func NewJSONStream(r io.Reader, w io.Writer, options ...JSONOption) Stream {
|
||||
s := &jsonStream{
|
||||
decoder: json.NewDecoder(r),
|
||||
encoder: json.NewEncoder(w),
|
||||
}
|
||||
for _, option := range options {
|
||||
option(s.encoder)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func JSONIndent(prefix, indent string) JSONOption {
|
||||
return func(e *json.Encoder) {
|
||||
e.SetIndent(prefix, indent)
|
||||
}
|
||||
}
|
||||
|
||||
func JSONEscapeHTML(on bool) JSONOption {
|
||||
return func(e *json.Encoder) {
|
||||
e.SetEscapeHTML(on)
|
||||
}
|
||||
}
|
||||
|
||||
func (s jsonStream) Encode(value any) error { return s.encoder.Encode(value) }
|
||||
func (s jsonStream) Decode(value any) error { return s.decoder.Decode(value) }
|
||||
|
||||
type yamlCodec struct{}
|
||||
|
||||
func (yamlCodec) Type() string { return "yaml" }
|
||||
func (yamlCodec) Encode(value any) ([]byte, error) { return yaml.Marshal(value) }
|
||||
func (yamlCodec) Decode(data []byte, value any) error { return yaml.Unmarshal(data, value) }
|
||||
|
||||
type yamlStream struct {
|
||||
decoder *yaml.Decoder
|
||||
encoder *yaml.Encoder
|
||||
}
|
||||
|
||||
func NewYaMLStream(r io.Reader, w io.Writer, options ...yaml.EncodeOption) Stream {
|
||||
s := &yamlStream{
|
||||
decoder: yaml.NewDecoder(r),
|
||||
encoder: yaml.NewEncoder(w),
|
||||
}
|
||||
for _, option := range options {
|
||||
option(s.encoder)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s yamlStream) Encode(value any) error { return s.encoder.Encode(value) }
|
||||
func (s yamlStream) Decode(value any) error { return s.decoder.Decode(value) }
|
Reference in New Issue
Block a user