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"
|
2024-08-15 15:12:42 +00:00
|
|
|
"log/slog"
|
2024-05-14 16:53:47 +00:00
|
|
|
"strings"
|
2024-08-15 15:12:42 +00:00
|
|
|
"google.golang.org/protobuf/proto"
|
2024-05-14 16:53:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
//type JSONDecoder json.Decoder
|
|
|
|
|
|
|
|
type Decoder interface {
|
|
|
|
Decode(v any) error
|
|
|
|
}
|
|
|
|
|
2024-07-01 07:16:55 +00:00
|
|
|
func NewDecoder(r io.Reader, format Format) Decoder {
|
|
|
|
switch format {
|
|
|
|
case FormatYaml:
|
|
|
|
return NewYAMLDecoder(r)
|
|
|
|
case FormatJson:
|
|
|
|
return NewJSONDecoder(r)
|
|
|
|
case FormatProtoBuf:
|
|
|
|
return NewProtoBufDecoder(r)
|
|
|
|
}
|
2024-05-14 16:53:47 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-08-15 15:12:42 +00:00
|
|
|
func NewStringDecoder(s string, format Format) Decoder {
|
|
|
|
return NewDecoder(strings.NewReader(s), format)
|
|
|
|
}
|
|
|
|
|
2024-05-14 16:53:47 +00:00
|
|
|
func NewJSONDecoder(r io.Reader) Decoder {
|
|
|
|
return json.NewDecoder(r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewJSONStringDecoder(s string) Decoder {
|
|
|
|
return json.NewDecoder(strings.NewReader(s))
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewYAMLDecoder(r io.Reader) Decoder {
|
2024-08-15 15:12:42 +00:00
|
|
|
slog.Info("NewYAMLDecoder()", "reader", r)
|
2024-05-14 16:53:47 +00:00
|
|
|
return yaml.NewDecoder(r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewYAMLStringDecoder(s string) Decoder {
|
|
|
|
return yaml.NewDecoder(strings.NewReader(s))
|
|
|
|
}
|
|
|
|
|
2024-08-15 15:12:42 +00:00
|
|
|
type ProtoDecoder struct {
|
|
|
|
reader io.Reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *ProtoDecoder) Decode(v any) (err error) {
|
|
|
|
var protoData []byte
|
|
|
|
protoData, err = io.ReadAll(p.reader)
|
2024-09-19 08:14:47 +00:00
|
|
|
if err == nil {
|
|
|
|
err = proto.Unmarshal(protoData, v.(proto.Message))
|
|
|
|
}
|
2024-08-15 15:12:42 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-14 16:53:47 +00:00
|
|
|
func NewProtoBufDecoder(r io.Reader) Decoder {
|
2024-08-15 15:12:42 +00:00
|
|
|
return &ProtoDecoder{ reader: r }
|
2024-05-14 16:53:47 +00:00
|
|
|
}
|