conf/adapters.go
Bruno Carlin e72c317bbb
All checks were successful
/ linting (push) Successful in 3m44s
/ tests (push) Successful in 27s
feat: add support for toml in addition to json
2024-05-06 11:19:26 +02:00

86 lines
1.5 KiB
Go

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
}