Skip to content

Commit

Permalink
adds support for yaml config
Browse files Browse the repository at this point in the history
  • Loading branch information
shubhang93 committed Aug 14, 2024
1 parent 4408c2a commit 1ffda47
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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=
31 changes: 28 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 1ffda47

Please sign in to comment.