conf/adapters.go

93 lines
1.9 KiB
Go

package conf
import (
"encoding/json"
"fmt"
"strings"
"github.com/pelletier/go-toml/v2"
)
type filetype int
const (
typeInvalid filetype = iota
typeJSON
typeTOML
)
// getType returns the type of the config file.
func getType(filename string) filetype {
switch {
case strings.HasSuffix(filename, ".json"):
return typeJSON
case strings.HasSuffix(filename, ".toml"):
return typeTOML
default:
return typeInvalid
}
}
// unmarshal unmarshals the given data to the given struct.
func unmarshal(ft filetype, data []byte, v any) error {
switch ft {
case typeJSON:
return unmarshalJSON(data, v)
case typeTOML:
return unmarshalTOML(data, v)
default:
return ErrUnsupportedFileType
}
}
// marshal marshals the given struct to bytes.
func marshal(ft filetype, v any) ([]byte, error) {
switch ft {
case typeJSON:
return marshalJSON(v)
case typeTOML:
return marshalTOML(v)
default:
return nil, ErrUnsupportedFileType
}
}
// unmarshalJSON unmarshals the given data to the given struct.
func unmarshalJSON(data []byte, v any) error {
err := json.Unmarshal(data, v)
if err != nil {
return fmt.Errorf("cannot parse config file: %w", err)
}
return nil
}
// marshalJSON marshals the given struct to bytes.
func marshalJSON(v any) ([]byte, error) {
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
return nil, fmt.Errorf("cannot generate config content: %w", err)
}
return data, nil
}
// unmarshalTOML unmarshals the given data to the given struct.
func unmarshalTOML(data []byte, v any) error {
err := toml.Unmarshal(data, v)
if err != nil {
return fmt.Errorf("cannot parse config file: %w", err)
}
return nil
}
// marshalTOML marshals the given struct to bytes.
func marshalTOML(v any) ([]byte, error) {
data, err := toml.Marshal(v)
if err != nil {
return nil, fmt.Errorf("cannot generate config content: %w", err)
}
return data, nil
}