Skip to content

Commit

Permalink
Error when unknown config parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
bartekn committed Feb 13, 2017
1 parent 4491b16 commit b45f11d
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
20 changes: 19 additions & 1 deletion support/config/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
package config

import (
"fmt"
"io/ioutil"

"github.com/BurntSushi/toml"
"github.com/asaskevich/govalidator"
"github.com/stellar/go/strkey"
Expand All @@ -18,11 +21,26 @@ type InvalidConfigError struct {
// Read takes the TOML configuration file at `path`, parses it into `dest` and
// then uses github.com/asaskevich/govalidator to validate the struct.
func Read(path string, dest interface{}) error {
_, err := toml.DecodeFile(path, dest)
bs, err := ioutil.ReadFile(path)
if err != nil {
return err
}
return decode(string(bs), dest)
}

func decode(content string, dest interface{}) error {
metadata, err := toml.Decode(content, dest)
if err != nil {
return errors.Wrap(err, "decode-file failed")
}

// Undecoded keys correspond to keys in the TOML document
// that do not have a concrete type in config struct.
undecoded := metadata.Undecoded()
if len(undecoded) > 0 {
return errors.New("Unknown fields: " + fmt.Sprintf("%+v", undecoded))
}

valid, err := govalidator.ValidateStruct(dest)

if valid {
Expand Down
39 changes: 39 additions & 0 deletions support/config/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,42 @@ func TestSeedValidator(t *testing.T) {
_, ok = fields["WrongType"]
assert.True(t, ok, "WrongType is not an invalid field")
}

func TestUndecoded(t *testing.T) {
var val struct {
Test string `toml:"test" valid:"optional"`
TLS struct {
CertificateFile string `toml:"certificate-file" valid:"optional"`
PrivateKeyFile string `toml:"private-key-file" valid:"optional"`
} `valid:"optional"`
}

// Notice _ in certificate_file
toml := `test="abc"
[tls]
certificate_file="hello"
private-key-file="world"`

err := decode(toml, &val)
require.Error(t, err)
assert.Equal(t, "Unknown fields: [tls.certificate_file]", err.Error())
}

func TestCorrect(t *testing.T) {
var val struct {
Test string `toml:"test" valid:"optional"`
TLS struct {
CertificateFile string `toml:"certificate-file" valid:"optional"`
PrivateKeyFile string `toml:"private-key-file" valid:"optional"`
} `valid:"optional"`
}

// Notice _ in certificate_file
toml := `test="abc"
[tls]
certificate-file="hello"
private-key-file="world"`

err := decode(toml, &val)
require.NoError(t, err)
}

0 comments on commit b45f11d

Please sign in to comment.