From 3b934bb910c5b887467c534d44af1449b0aa32e3 Mon Sep 17 00:00:00 2001 From: Christoph Portmann Date: Wed, 11 Jun 2014 11:33:32 +0300 Subject: [PATCH] config: fix error when json config starts with an array --- config/json.go | 7 ++++++- config/json_test.go | 47 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/config/json.go b/config/json.go index a24f9dd6..440d98bf 100644 --- a/config/json.go +++ b/config/json.go @@ -35,7 +35,12 @@ func (js *JsonConfig) Parse(filename string) (ConfigContainer, error) { } err = json.Unmarshal(content, &x.data) if err != nil { - return nil, err + var wrappingArray []interface{} + err2 := json.Unmarshal(content, &wrappingArray) + if err2 != nil { + return nil, err + } + x.data["rootArray"] = wrappingArray } return x, nil } diff --git a/config/json_test.go b/config/json_test.go index e0046084..a2741941 100644 --- a/config/json_test.go +++ b/config/json_test.go @@ -33,6 +33,53 @@ var jsoncontext = `{ } }` +var jsoncontextwitharray = `[ + { + "url": "user", + "serviceAPI": "http://www.test.com/user" + }, + { + "url": "employee", + "serviceAPI": "http://www.test.com/employee" + } +]` + +func TestJsonStartsWithArray(t *testing.T) { + f, err := os.Create("testjsonWithArray.conf") + if err != nil { + t.Fatal(err) + } + _, err = f.WriteString(jsoncontextwitharray) + if err != nil { + f.Close() + t.Fatal(err) + } + f.Close() + defer os.Remove("testjsonWithArray.conf") + jsonconf, err := NewConfig("json", "testjsonWithArray.conf") + if err != nil { + t.Fatal(err) + } + rootArray, err := jsonconf.DIY("rootArray") + if (err != nil) { + t.Error("array does not exist as element") + } + rootArrayCasted := rootArray.([]interface{}) + if (rootArrayCasted == nil) { + t.Error("array from root is nil") + }else { + elem := rootArrayCasted[0].(map[string]interface{}) + if elem["url"] != "user" || elem["serviceAPI"] != "http://www.test.com/user" { + t.Error("array[0] values are not valid") + } + + elem2 := rootArrayCasted[1].(map[string]interface{}) + if elem2["url"] != "employee" || elem2["serviceAPI"] != "http://www.test.com/employee" { + t.Error("array[1] values are not valid") + } + } +} + func TestJson(t *testing.T) { f, err := os.Create("testjson.conf") if err != nil {