jx/internal/codec/types.go
Matthew Rich 52c083a3d9
Some checks failed
Lint / golangci-lint (push) Failing after 9m44s
Declarative Tests / test (push) Failing after 14s
Declarative Tests / build-fedora (push) Failing after 2m50s
Declarative Tests / build-ubuntu-focal (push) Failing after 1m3s
add source for containers, packages
2024-07-01 00:16:55 -07:00

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)
}