Skip to content

Commit

Permalink
feat: Allow reading config from env vars (#152)
Browse files Browse the repository at this point in the history
  • Loading branch information
soerenschneider authored Aug 18, 2022
1 parent 7081e88 commit 4b7f669
Show file tree
Hide file tree
Showing 9 changed files with 102 additions and 14 deletions.
18 changes: 11 additions & 7 deletions cmd/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"flag"
"fmt"
"github.com/caarlos0/env/v6"
"github.com/rs/zerolog/log"
"github.com/soerenschneider/dyndns/client"
"github.com/soerenschneider/dyndns/client/resolvers"
Expand All @@ -26,8 +27,8 @@ var configPathPreferences = []string{

func main() {
metrics.Version.WithLabelValues(internal.BuildVersion, internal.CommitHash).SetToCurrentTime()
defaultConfigPath := checkDefaultConfigFiles()
configPath := flag.String("config", defaultConfigPath, "Path to the config file")

configPath := flag.String("config", "", "Path to the config file")
once := flag.Bool("once", false, "Do not run as a daemon")
version := flag.Bool("version", false, "Print version and exit")
flag.Parse()
Expand All @@ -38,21 +39,24 @@ func main() {
}

util.InitLogging()
if nil == configPath {
log.Fatal().Msgf("No config path supplied")
if *configPath == "" {
*configPath = getDefaultConfigFileOrEmpty()
}

conf, err := conf.ReadClientConfig(*configPath)
if err != nil {
log.Fatal().Msgf("couldn't read config file: %v", err)
}
if err := env.Parse(conf); err != nil {
log.Fatal().Msgf("%+v\n", err)
}

// supply once flag value
conf.Once = *once
conf.Print()
RunClient(conf)
}

func checkDefaultConfigFiles() string {
func getDefaultConfigFileOrEmpty() string {
for _, configPath := range configPathPreferences {
if strings.HasPrefix(configPath, "~/") {
configPath = path.Join(getUserHomeDirectory(), configPath[2:])
Expand All @@ -65,7 +69,7 @@ func checkDefaultConfigFiles() string {
}
}

return configPathPreferences[0]
return ""
}

func getUserHomeDirectory() string {
Expand Down
14 changes: 9 additions & 5 deletions conf/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import (
"fmt"
"github.com/rs/zerolog/log"
"github.com/soerenschneider/dyndns/internal/metrics"
"io/ioutil"
"os"
)

type ClientConf struct {
Host string `json:"host"`
KeyPairPath string `json:"keypair_path"`
MetricsListener string `json:"metrics_listen",omitempty`
Host string `json:"host" env:"DYNDNS_HOST"`
KeyPairPath string `json:"keypair_path" env:"DYNDNS_KEYPAIR_PATH"`
MetricsListener string `json:"metrics_listen",omitempty env:"DYNDNS_METRICS_LISTEN`
Once bool // this is not parsed via json, it's an cli flag
MqttConfig
*InterfaceConfig
Expand Down Expand Up @@ -59,7 +59,11 @@ func getDefaultClientConfig() *ClientConf {
}

func ReadClientConfig(path string) (*ClientConf, error) {
content, err := ioutil.ReadFile(path)
if path == "" {
return &ClientConf{}, nil
}

content, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("could not read config file %s: %v", path, err)
}
Expand Down
69 changes: 69 additions & 0 deletions conf/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package conf

import (
"reflect"
"testing"
)

func TestReadClientConfig(t *testing.T) {
type args struct {
path string
}
tests := []struct {
name string
args args
want *ClientConf
wantErr bool
}{
{
name: "happy path",
args: args{"../contrib/client.json"},
want: &ClientConf{
Host: "my.host.tld",
KeyPairPath: "/keypair.json",
MetricsListener: ":9191",
MqttConfig: MqttConfig{
Brokers: []string{"broker-1", "broker-2"},
ClientId: "my-client-id",
},
},
wantErr: false,
},
{
name: "non-existing-file",
args: args{"some-file"},
want: nil,
wantErr: true,
},
{
name: "wrong format",
args: args{"../contrib/textfile.txt"},
want: nil,
wantErr: true,
},
{
name: "empty json file content",
args: args{"../contrib/empty.json"},
want: getDefaultClientConfig(),
wantErr: false,
},
{
name: "empty path",
args: args{""},
want: &ClientConf{},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ReadClientConfig(tt.args.path)
if (err != nil) != tt.wantErr {
t.Errorf("ReadClientConfig() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("ReadClientConfig() got = %v, want %v", got, tt.want)
}
})
}
}
4 changes: 2 additions & 2 deletions conf/mqtt.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import (
)

type MqttConfig struct {
Brokers []string `json:"brokers"`
ClientId string `json:"client_id"`
Brokers []string `json:"brokers" env:"DYNDNS_BROKERS" envSeparator:";"`
ClientId string `json:"client_id" env:"DYNDNS_CLIENT_ID"`
}

func (conf *MqttConfig) Print() {
Expand Down
6 changes: 6 additions & 0 deletions contrib/client.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"host": "my.host.tld",
"keypair_path": "/keypair.json",
"client_id": "my-client-id",
"brokers": ["broker-1", "broker-2"]
}
1 change: 1 addition & 0 deletions contrib/empty.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions contrib/textfile.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
no json here
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.17

require (
github.com/aws/aws-sdk-go v1.44.76
github.com/caarlos0/env/v6 v6.9.3
github.com/eclipse/paho.mqtt.golang v1.4.1
github.com/hashicorp/go-retryablehttp v0.7.1
github.com/prometheus/client_golang v1.13.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/caarlos0/env/v6 v6.9.3 h1:Tyg69hoVXDnpO5Qvpsu8EoquarbPyQb+YwExWHP8wWU=
github.com/caarlos0/env/v6 v6.9.3/go.mod h1:hvp/ryKXKipEkcuYjs9mI4bBCg+UI0Yhgm5Zu0ddvwc=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
Expand Down

0 comments on commit 4b7f669

Please sign in to comment.