diff --git a/go.mod b/go.mod index 0bfc3b2..0cbbacf 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,7 @@ module github.com/shubhang93/tplagent go 1.22.1 -require github.com/google/go-cmp v0.6.0 +require ( + github.com/google/go-cmp v0.6.0 + gopkg.in/yaml.v3 v3.0.1 +) diff --git a/go.sum b/go.sum index 5a8d551..21b05ad 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,6 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/config/config.go b/internal/config/config.go index f0407fd..059c91f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,9 +6,11 @@ import ( "fmt" "github.com/shubhang93/tplagent/internal/duration" "github.com/shubhang93/tplagent/internal/fatal" + "gopkg.in/yaml.v3" "io" "log/slog" "os" + "path/filepath" "time" "unicode" ) @@ -61,16 +63,39 @@ type TPLAgent struct { } func ReadFromFile(path string) (TPLAgent, error) { - confFile, err := os.Open(os.ExpandEnv(path)) + + expandedPath := os.ExpandEnv(path) + confFile, err := os.Open(expandedPath) if err != nil { return TPLAgent{}, fatal.NewError(fmt.Errorf("read config:%w", err)) } - return Read(confFile, "json") + + ext := filepath.Ext(expandedPath) + if len(ext) > 0 { + ext = ext[1:] + } + + return Read(confFile, ext) +} + +type decoder interface { + Decode(v any) error } func Read(rr io.Reader, configFormat string) (TPLAgent, error) { var c TPLAgent - if err := json.NewDecoder(rr).Decode(&c); err != nil { + + var cfgDecoder decoder + switch configFormat { + case "json": + cfgDecoder = json.NewDecoder(rr) + case "yaml,yml": + cfgDecoder = yaml.NewDecoder(rr) + default: + return TPLAgent{}, fmt.Errorf("unknown config format:%s", configFormat) + } + + if err := cfgDecoder.Decode(&c); err != nil { return TPLAgent{}, fatal.NewError(fmt.Errorf("config decode error:%w", err)) } if err := Validate(&c); err != nil {