107 lines
1.9 KiB
Go
107 lines
1.9 KiB
Go
|
package config
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"github.com/go-playground/validator/v10"
|
||
|
"io"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
|
||
|
"github.com/pelletier/go-toml/v2"
|
||
|
"gopkg.in/yaml.v3"
|
||
|
)
|
||
|
|
||
|
type FileType string
|
||
|
|
||
|
const (
|
||
|
YAML FileType = "yaml"
|
||
|
TOML FileType = "toml"
|
||
|
JSON FileType = "json"
|
||
|
)
|
||
|
|
||
|
// getFileType returns the file type based on the file extension.
|
||
|
func getFileType(path string) (FileType, error) {
|
||
|
// Get the file extension
|
||
|
ext := filepath.Ext(path)
|
||
|
|
||
|
switch ext {
|
||
|
case ".yaml", ".yml":
|
||
|
return YAML, nil
|
||
|
case ".toml":
|
||
|
return TOML, nil
|
||
|
case ".json":
|
||
|
return JSON, nil
|
||
|
default:
|
||
|
return "", fmt.Errorf("unsupported file type: %s", ext)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func ParseConfig(path string) (Config, error) {
|
||
|
fileType, err := getFileType(path)
|
||
|
if err != nil {
|
||
|
return Config{}, err
|
||
|
}
|
||
|
|
||
|
file, err := os.Open(path)
|
||
|
if err != nil {
|
||
|
return Config{}, err
|
||
|
}
|
||
|
defer file.Close()
|
||
|
|
||
|
data, err := io.ReadAll(file)
|
||
|
|
||
|
var config Config
|
||
|
|
||
|
switch fileType {
|
||
|
case YAML:
|
||
|
config, err = parseYAML(data)
|
||
|
case TOML:
|
||
|
config, err = parseTOML(data)
|
||
|
case JSON:
|
||
|
config, err = parseJSON(data)
|
||
|
default:
|
||
|
return Config{}, fmt.Errorf("unsupported file type: %s", fileType)
|
||
|
}
|
||
|
|
||
|
if err != nil {
|
||
|
return Config{}, err
|
||
|
}
|
||
|
|
||
|
validate := validator.New(validator.WithRequiredStructEnabled())
|
||
|
err = validate.Struct(config)
|
||
|
|
||
|
if err != nil {
|
||
|
return Config{}, err
|
||
|
}
|
||
|
|
||
|
return config, nil
|
||
|
}
|
||
|
|
||
|
func parseTOML(data []byte) (Config, error) {
|
||
|
var appConfig Config
|
||
|
err := toml.Unmarshal(data, &appConfig)
|
||
|
if err != nil {
|
||
|
return Config{}, err
|
||
|
}
|
||
|
return appConfig, nil
|
||
|
}
|
||
|
|
||
|
func parseYAML(data []byte) (Config, error) {
|
||
|
var appConfig Config
|
||
|
err := yaml.Unmarshal(data, &appConfig)
|
||
|
if err != nil {
|
||
|
return Config{}, err
|
||
|
}
|
||
|
return appConfig, nil
|
||
|
}
|
||
|
|
||
|
func parseJSON(data []byte) (Config, error) {
|
||
|
var appConfig Config
|
||
|
err := json.Unmarshal(data, &appConfig)
|
||
|
if err != nil {
|
||
|
return Config{}, err
|
||
|
}
|
||
|
return appConfig, nil
|
||
|
}
|