conf/adapters.go

87 lines
1.5 KiB
Go
Raw Normal View History

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