go-ipfs-config: add a Clone function
The user must call this before modifying the config. Given that the config contains slices/maps modifications can modified *shared* state, even after dereferencing.
Steven Allen committed
Oct 23, 2018 at 09:47 UTC
b627585f2826938f964cbb5a44b5f710d08bdeee
2 files changed
+39
config/config.go
+16
@@ -110,3 +110,19 @@ func ToMap(conf *Config) (map[string]interface{}, error) {
110
}
111
return m, nil
112
}
113
+
114
+// Clone copies the config. Use when updating.
115
+func (c *Config) Clone() (*Config, error) {
116
+ var newConfig Config
117
+ var buf bytes.Buffer
118
+
119
+ if err := json.NewEncoder(&buf).Encode(c); err != nil {
120
+ return nil, fmt.Errorf("failure to encode config: %s", err)
121
+ }
122
+
123
+ if err := json.NewDecoder(&buf).Decode(&newConfig); err != nil {
124
+ return nil, fmt.Errorf("failure to decode config: %s", err)
125
+ }
126
+
127
+ return &newConfig, nil
128
+}
config/config_test.go
new
+23
@@ -0,0 +1,23 @@
1
+package config
2
+
3
+import (
4
+ "testing"
5
+)
6
+
7
+func TestClone(t *testing.T) {
8
+ c := new(Config)
9
+ c.Identity.PeerID = "faketest"
10
+ c.API.HTTPHeaders = map[string][]string{"foo": []string{"bar"}}
11
+
12
+ newCfg, err := c.Clone()
13
+ if err != nil {
14
+ t.Fatal(err)
15
+ }
16
+ if newCfg.Identity.PeerID != c.Identity.PeerID {
17
+ t.Fatal("peer ID not preserved")
18
+ }
19
+ delete(c.API.HTTPHeaders, "foo")
20
+ if newCfg.API.HTTPHeaders["foo"][0] != "bar" {
21
+ t.Fatal("HTTP headers not preserved")
22
+ }
23
+}