jx/internal/codec/encoder.go

77 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-05-14 16:53:47 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package codec
import (
"encoding/json"
_ "fmt"
_ "github.com/xeipuuv/gojsonschema"
"gopkg.in/yaml.v3"
"io"
_ "log"
2024-08-18 01:16:02 +00:00
"errors"
"google.golang.org/protobuf/proto"
2024-05-14 16:53:47 +00:00
)
2024-08-18 01:16:02 +00:00
var ErrInvalidWriter error = errors.New("Invalid writer")
2024-05-14 16:53:47 +00:00
type JSONEncoder json.Encoder
type Encoder interface {
Encode(v any) error
Close() error
}
2024-07-01 07:16:55 +00:00
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)
}
2024-05-14 16:53:47 +00:00
return nil
}
func NewJSONEncoder(w io.Writer) Encoder {
return (*JSONEncoder)(json.NewEncoder(w))
}
func NewYAMLEncoder(w io.Writer) Encoder {
return yaml.NewEncoder(w)
}
2024-08-18 01:16:02 +00:00
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
}
2024-05-14 16:53:47 +00:00
func NewProtoBufEncoder(w io.Writer) Encoder {
2024-08-18 01:16:02 +00:00
if w != nil {
return &ProtoEncoder{ writer: w }
}
2024-05-14 16:53:47 +00:00
return nil
}
func (j *JSONEncoder) Encode(v any) error {
return (*json.Encoder)(j).Encode(v)
}
func (j *JSONEncoder) Close() error {
return nil
}