commit dd0af5f789c1bac0444c33fcc4434922be48d1e7
parent e2cace7fed7b46be01306cd0b4e94093b0bdcec2
Author: Oliver Lowe <o@olowe.co>
Date: Tue, 18 Jan 2022 23:59:27 +1100
Correctly marshal Hosts into JSON
We were missing some attributes, like not adding any groups or display
names. This also adds a test which checks whether we are marshalling
hosts into JSON correctly.
Diffstat:
| M | host.go | | | 25 | ++++++++++--------------- |
| A | host_test.go | | | 38 | ++++++++++++++++++++++++++++++++++++++ |
2 files changed, 48 insertions(+), 15 deletions(-)
diff --git a/host.go b/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) {
diff --git a/host_test.go b/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)
+}