62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
|
|
|
package codec
|
|
|
|
import (
|
|
"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 ErrInvalidFormat
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|