diff --git a/config/serialize/serialize.go b/config/serialize/serialize.go index d20e48118f5f..6c7721340678 100644 --- a/config/serialize/serialize.go +++ b/config/serialize/serialize.go @@ -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 } @@ -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. diff --git a/config/serialize/serialize_test.go b/config/serialize/serialize_test.go index cc161c80dbd3..e53a2d1f066e 100644 --- a/config/serialize/serialize_test.go +++ b/config/serialize/serialize_test.go @@ -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) + } +}