jx/internal/codec/types.go
Matthew Rich a6426da6e1
Some checks failed
Lint / golangci-lint (push) Successful in 9m53s
Declarative Tests / test (push) Failing after 5s
Declarative Tests / build-fedora (push) Successful in 2m12s
Declarative Tests / build-ubuntu-focal (push) Successful in 1m21s
add support for RSA keys/certs
2024-07-17 01:34:57 -07:00

81 lines
1.6 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package codec
import (
"io"
"fmt"
"errors"
"encoding/json"
"gopkg.in/yaml.v3"
)
const (
FormatYaml Format = "yaml"
FormatJson Format = "json"
FormatProtoBuf Format = "protobuf"
)
var ErrInvalidFormat error = errors.New("invalid Format value")
type Format string
func (f *Format) Validate() error {
switch *f {
case FormatYaml, FormatJson, FormatProtoBuf:
return nil
default:
return fmt.Errorf("%w: %s", ErrInvalidFormat, *f)
}
}
func (f *Format) Set(value string) (err error) {
if err = (*Format)(&value).Validate(); err == nil {
*f = Format(value)
}
return
}
func (f *Format) UnmarshalValue(value string) error {
switch value {
case string(FormatYaml), string(FormatJson), string(FormatProtoBuf):
*f = Format(value)
return nil
default:
return ErrInvalidFormat
}
}
func (f *Format) UnmarshalJSON(data []byte) error {
var s string
if unmarshalFormatTypeErr := json.Unmarshal(data, &s); unmarshalFormatTypeErr != nil {
return unmarshalFormatTypeErr
}
return f.UnmarshalValue(s)
}
func (f *Format) UnmarshalYAML(value *yaml.Node) error {
var s string
if err := value.Decode(&s); err != nil {
return err
}
return f.UnmarshalValue(s)
}
func (f Format) Encoder(w io.Writer) Encoder {
return NewEncoder(w, f)
}
func (f Format) Decoder(r io.Reader) Decoder {
return NewDecoder(r, f)
}
func (f Format) Serialize(object any, w io.Writer) error {
return f.Encoder(w).Encode(object)
}
func (f Format) Deserialize(r io.Reader, object any) error {
return f.Decoder(r).Decode(object)
}