Skip to content

Commit

Permalink
Avoid unknown fields on config
Browse files Browse the repository at this point in the history
This will reduce headaches when adding the wrong fields to the config.

Signed-off-by: Antonio Navarro Perez <antnavper@gmail.com>
  • Loading branch information
ajnavarro committed Nov 30, 2022
1 parent c8a4b6a commit c71844b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
18 changes: 10 additions & 8 deletions config/serialize/serialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,14 @@ func ReadConfigFile(filename string, cfg interface{}) error {
return err
}
defer f.Close()
if err := json.NewDecoder(f).Decode(cfg); err != nil {

dec := json.NewDecoder(f)
dec.DisallowUnknownFields()

if err := dec.Decode(cfg); err != nil {
return fmt.Errorf("failure to decode config: %s", err)
}

return nil
}

Expand All @@ -51,13 +56,10 @@ func WriteConfigFile(filename string, cfg interface{}) error {

// encode configuration with JSON
func encode(w io.Writer, value interface{}) error {
// need to prettyprint, hence MarshalIndent, instead of Encoder
buf, err := config.Marshal(value)
if err != nil {
return err
}
_, err = w.Write(buf)
return err
enc := json.NewEncoder(w)
enc.SetIndent("", " ")

return enc.Encode(value)
}

// Load reads given file and returns the read config, or error.
Expand Down
22 changes: 22 additions & 0 deletions config/serialize/serialize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,25 @@ func TestConfig(t *testing.T) {
}
}
}

func TestConfigUnknownField(t *testing.T) {
const filename = ".ipfsconfig"

badConfig := map[string]string{
"BadField": "Value",
}

err := WriteConfigFile(filename, badConfig)
if err != nil {
t.Fatal(err)
}

_, err = Load(filename)
if err == nil {
t.Fatal("load must fail")
}

if err.Error() != "failure to decode config: json: unknown field \"BadField\"" {
t.Fatal("unexpected error:", err)
}
}

0 comments on commit c71844b

Please sign in to comment.