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