mirror of
https://github.com/ipfs/kubo.git
synced 2026-03-10 18:57:57 +08:00
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.
This commit is contained in:
parent
16f3d2269a
commit
b627585f28
@ -110,3 +110,19 @@ func ToMap(conf *Config) (map[string]interface{}, error) {
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Clone copies the config. Use when updating.
|
||||
func (c *Config) Clone() (*Config, error) {
|
||||
var newConfig Config
|
||||
var buf bytes.Buffer
|
||||
|
||||
if err := json.NewEncoder(&buf).Encode(c); err != nil {
|
||||
return nil, fmt.Errorf("failure to encode config: %s", err)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(&buf).Decode(&newConfig); err != nil {
|
||||
return nil, fmt.Errorf("failure to decode config: %s", err)
|
||||
}
|
||||
|
||||
return &newConfig, nil
|
||||
}
|
||||
|
||||
23
config/config_test.go
Normal file
23
config/config_test.go
Normal file
@ -0,0 +1,23 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClone(t *testing.T) {
|
||||
c := new(Config)
|
||||
c.Identity.PeerID = "faketest"
|
||||
c.API.HTTPHeaders = map[string][]string{"foo": []string{"bar"}}
|
||||
|
||||
newCfg, err := c.Clone()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if newCfg.Identity.PeerID != c.Identity.PeerID {
|
||||
t.Fatal("peer ID not preserved")
|
||||
}
|
||||
delete(c.API.HTTPHeaders, "foo")
|
||||
if newCfg.API.HTTPHeaders["foo"][0] != "bar" {
|
||||
t.Fatal("HTTP headers not preserved")
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user