Skip to content

Commit ae8b023

Browse files
committed
Merge pull request #34 from ryansb/bug/metadataSerialization
Fix instance metadata XML serialization
2 parents 2006552 + bf62a00 commit ae8b023

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

marshal.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ package fargo
44

55
import (
66
"encoding/json"
7+
"encoding/xml"
78
"strconv"
89
)
910

@@ -120,3 +121,26 @@ func (i *InstanceMetadata) MarshalJSON() ([]byte, error) {
120121

121122
return i.Raw, nil
122123
}
124+
125+
// MarshalXML is a custom XML marshaler for InstanceMetadata.
126+
func (i InstanceMetadata) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
127+
tokens := []xml.Token{start}
128+
129+
if i.parsed != nil {
130+
for key, value := range i.parsed {
131+
t := xml.StartElement{Name: xml.Name{"", key}}
132+
tokens = append(tokens, t, xml.CharData(value.(string)), xml.EndElement{t.Name})
133+
}
134+
}
135+
tokens = append(tokens, xml.EndElement{start.Name})
136+
137+
for _, t := range tokens {
138+
err := e.EncodeToken(t)
139+
if err != nil {
140+
return err
141+
}
142+
}
143+
144+
// flush to ensure tokens are written
145+
return e.Flush()
146+
}

tests/metadata_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package fargo_test
33
// MIT Licensed (see README.md) - Copyright (c) 2013 Hudl <@Hudl>
44

55
import (
6+
"encoding/xml"
67
"github.com/hudl/fargo"
78
. "github.com/smartystreets/goconvey/convey"
89
"strconv"
@@ -58,3 +59,28 @@ func TestGetFloat(t *testing.T) {
5859
})
5960
})
6061
}
62+
63+
func TestSerializeMeta(t *testing.T) {
64+
Convey("Given an instance", t, func() {
65+
instance := new(fargo.Instance)
66+
Convey("With metadata", func() {
67+
instance.SetMetadataString("test", "value")
68+
Convey("Serializing results in correct JSON", func() {
69+
b, err := instance.Metadata.MarshalJSON()
70+
So(err, ShouldBeNil)
71+
So(string(b), ShouldEqual, "{\"test\":\"value\"}")
72+
})
73+
Convey("Serializing results in correct XML", func() {
74+
b, err := xml.Marshal(instance.Metadata)
75+
So(err, ShouldBeNil)
76+
So(string(b), ShouldEqual, "<InstanceMetadata><test>value</test></InstanceMetadata>")
77+
})
78+
Convey("Blank metadata results in blank XML", func() {
79+
metadata := new(fargo.InstanceMetadata)
80+
b, err := xml.Marshal(metadata)
81+
So(err, ShouldBeNil)
82+
So(string(b), ShouldEqual, "<InstanceMetadata></InstanceMetadata>")
83+
})
84+
})
85+
})
86+
}

0 commit comments

Comments
 (0)