// Copyright 2024 Matthew Rich . All rights reserved. package codec import ( "encoding/json" _ "fmt" _ "github.com/xeipuuv/gojsonschema" "gopkg.in/yaml.v3" "io" _ "log" "errors" "google.golang.org/protobuf/proto" ) var ErrInvalidWriter error = errors.New("Invalid writer") type JSONEncoder json.Encoder type Encoder interface { Encode(v any) error Close() error } func NewEncoder(w io.Writer, format Format) Encoder { switch format { case FormatYaml: return NewYAMLEncoder(w) case FormatJson: return NewJSONEncoder(w) case FormatProtoBuf: return NewProtoBufEncoder(w) } return nil } func NewJSONEncoder(w io.Writer) Encoder { return (*JSONEncoder)(json.NewEncoder(w)) } func NewYAMLEncoder(w io.Writer) Encoder { return yaml.NewEncoder(w) } type ProtoEncoder struct { writer io.Writer } func (p *ProtoEncoder) Encode(v any) (err error) { var encoded []byte encoded, err = proto.Marshal(v.(proto.Message)) if err != nil { return } _, err = p.writer.Write(encoded) return } func (p *ProtoEncoder) Close() error { return nil } func NewProtoBufEncoder(w io.Writer) Encoder { if w != nil { return &ProtoEncoder{ writer: w } } return nil } func (j *JSONEncoder) Encode(v any) error { return (*json.Encoder)(j).Encode(v) } func (j *JSONEncoder) Close() error { return nil }