diff --git a/config/config.go b/config/config.go index 44b700f1141..dc987547951 100644 --- a/config/config.go +++ b/config/config.go @@ -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 +} diff --git a/config/config_test.go b/config/config_test.go new file mode 100644 index 00000000000..dead06f8a23 --- /dev/null +++ b/config/config_test.go @@ -0,0 +1,29 @@ +package config + +import ( + "testing" +) + +func TestClone(t *testing.T) { + c := new(Config) + c.Identity.PeerID = "faketest" + c.API.HTTPHeaders = map[string][]string{"foo": {"bar"}} + + newCfg, err := c.Clone() + if err != nil { + t.Fatal(err) + } + if newCfg.Identity.PeerID != c.Identity.PeerID { + t.Fatal("peer ID not preserved") + } + + c.API.HTTPHeaders["foo"] = []string{"baz"} + if newCfg.API.HTTPHeaders["foo"][0] != "bar" { + t.Fatal("HTTP headers not preserved") + } + + delete(c.API.HTTPHeaders, "foo") + if newCfg.API.HTTPHeaders["foo"][0] != "bar" { + t.Fatal("HTTP headers not preserved") + } +} diff --git a/config/types_test.go b/config/types_test.go new file mode 100644 index 00000000000..7523962ae83 --- /dev/null +++ b/config/types_test.go @@ -0,0 +1,53 @@ +package config + +import ( + "encoding/json" + "testing" +) + +func TestOneStrings(t *testing.T) { + out, err := json.Marshal(Strings{"one"}) + if err != nil { + t.Fatal(err) + + } + expected := "\"one\"" + if string(out) != expected { + t.Fatalf("expected %s, got %s", expected, string(out)) + } +} + +func TestNoStrings(t *testing.T) { + out, err := json.Marshal(Strings{}) + if err != nil { + t.Fatal(err) + + } + expected := "null" + if string(out) != expected { + t.Fatalf("expected %s, got %s", expected, string(out)) + } +} + +func TestManyStrings(t *testing.T) { + out, err := json.Marshal(Strings{"one", "two"}) + if err != nil { + t.Fatal(err) + + } + expected := "[\"one\",\"two\"]" + if string(out) != expected { + t.Fatalf("expected %s, got %s", expected, string(out)) + } +} + +func TestFunkyStrings(t *testing.T) { + toParse := " [ \"one\", \"two\" ] " + var s Strings + if err := json.Unmarshal([]byte(toParse), &s); err != nil { + t.Fatal(err) + } + if len(s) != 2 || s[0] != "one" && s[1] != "two" { + t.Fatalf("unexpected result: %v", s) + } +}