Commit Diff


commit - e2cace7fed7b46be01306cd0b4e94093b0bdcec2
commit + dd0af5f789c1bac0444c33fcc4434922be48d1e7
blob - 7e5c3866feeda7b532b0ca8054e215db08634734
blob + 8d2a29608d46ada07a8e8bbfb1201d0bfd091264
--- host.go
+++ host.go
@@ -57,22 +57,17 @@ func (hg HostGroup) path() string {
 }
 
 func (h Host) MarshalJSON() ([]byte, error) {
-	type Attrs struct {
-		Address      string `json:"address"`
-		CheckCommand string `json:"check_command"`
-		DisplayName  string `json:"display_name"`
+	attrs := make(map[string]interface{})
+	attrs["address"] = h.Address
+	attrs["address6"] = h.Address6
+	if len(h.Groups) > 0 {
+		attrs["groups"] = h.Groups
 	}
-	type host struct {
-		Attrs Attrs `json:"attrs"`
-	}
-	jhost := &host{
-		Attrs: Attrs{
-			Address:      h.Address,
-			CheckCommand: h.CheckCommand,
-			DisplayName:  h.DisplayName,
-		},
-	}
-	return json.Marshal(jhost)
+	attrs["check_command"] = h.CheckCommand
+	attrs["display_name"] = h.DisplayName
+	m := make(map[string]interface{})
+	m["attrs"] = attrs
+	return json.Marshal(m)
 }
 
 func (hg HostGroup) MarshalJSON() ([]byte, error) {
blob - /dev/null
blob + 153f8e25fc2c57e87eb5299b495cbe71bb19a290 (mode 644)
--- /dev/null
+++ host_test.go
@@ -0,0 +1,38 @@
+package icinga
+
+import (
+	"encoding/json"
+	"reflect"
+	"testing"
+)
+
+func TestHostMarshal(t *testing.T) {
+	s := `{"attrs":{"address":"192.0.2.1","address6":"2001:db8::","groups":["test"],"check_command":"dummy","display_name":"Example host"}}`
+	want := make(map[string]interface{})
+	if err := json.Unmarshal([]byte(s), &want); err != nil {
+		t.Fatal(err)
+	}
+
+	p, err := json.Marshal(Host{
+		Name:         "example.com",
+		Address:      "192.0.2.1",
+		Address6:     "2001:db8::",
+		Groups:       []string{"test"},
+		State:        HostDown,
+		StateType:    StateSoft,
+		CheckCommand: "dummy",
+		DisplayName:  "Example host",
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	got := make(map[string]interface{})
+	if err := json.Unmarshal(p, &got); err != nil {
+		t.Fatal(err)
+	}
+
+	if !reflect.DeepEqual(want, got) {
+		t.Fail()
+	}
+	t.Log("want", want, "got", got)
+}