Skip to content

Commit c71844b

Browse files
committed
Avoid unknown fields on config
This will reduce headaches when adding the wrong fields to the config. Signed-off-by: Antonio Navarro Perez <[email protected]>
1 parent c8a4b6a commit c71844b

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

config/serialize/serialize.go

+10-8
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,14 @@ func ReadConfigFile(filename string, cfg interface{}) error {
2727
return err
2828
}
2929
defer f.Close()
30-
if err := json.NewDecoder(f).Decode(cfg); err != nil {
30+
31+
dec := json.NewDecoder(f)
32+
dec.DisallowUnknownFields()
33+
34+
if err := dec.Decode(cfg); err != nil {
3135
return fmt.Errorf("failure to decode config: %s", err)
3236
}
37+
3338
return nil
3439
}
3540

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

5257
// encode configuration with JSON
5358
func encode(w io.Writer, value interface{}) error {
54-
// need to prettyprint, hence MarshalIndent, instead of Encoder
55-
buf, err := config.Marshal(value)
56-
if err != nil {
57-
return err
58-
}
59-
_, err = w.Write(buf)
60-
return err
59+
enc := json.NewEncoder(w)
60+
enc.SetIndent("", " ")
61+
62+
return enc.Encode(value)
6163
}
6264

6365
// Load reads given file and returns the read config, or error.

config/serialize/serialize_test.go

+22
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,25 @@ func TestConfig(t *testing.T) {
3535
}
3636
}
3737
}
38+
39+
func TestConfigUnknownField(t *testing.T) {
40+
const filename = ".ipfsconfig"
41+
42+
badConfig := map[string]string{
43+
"BadField": "Value",
44+
}
45+
46+
err := WriteConfigFile(filename, badConfig)
47+
if err != nil {
48+
t.Fatal(err)
49+
}
50+
51+
_, err = Load(filename)
52+
if err == nil {
53+
t.Fatal("load must fail")
54+
}
55+
56+
if err.Error() != "failure to decode config: json: unknown field \"BadField\"" {
57+
t.Fatal("unexpected error:", err)
58+
}
59+
}

0 commit comments

Comments
 (0)