Skip to content

Commit

Permalink
Merge pull request #34 from ryansb/bug/metadataSerialization
Browse files Browse the repository at this point in the history
Fix instance metadata XML serialization
  • Loading branch information
ryansb committed Dec 12, 2015
2 parents 2006552 + bf62a00 commit ae8b023
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
24 changes: 24 additions & 0 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package fargo

import (
"encoding/json"
"encoding/xml"
"strconv"
)

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

return i.Raw, nil
}

// MarshalXML is a custom XML marshaler for InstanceMetadata.
func (i InstanceMetadata) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
tokens := []xml.Token{start}

if i.parsed != nil {
for key, value := range i.parsed {
t := xml.StartElement{Name: xml.Name{"", key}}
tokens = append(tokens, t, xml.CharData(value.(string)), xml.EndElement{t.Name})
}
}
tokens = append(tokens, xml.EndElement{start.Name})

for _, t := range tokens {
err := e.EncodeToken(t)
if err != nil {
return err
}
}

// flush to ensure tokens are written
return e.Flush()
}
26 changes: 26 additions & 0 deletions tests/metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package fargo_test
// MIT Licensed (see README.md) - Copyright (c) 2013 Hudl <@Hudl>

import (
"encoding/xml"
"github.com/hudl/fargo"
. "github.com/smartystreets/goconvey/convey"
"strconv"
Expand Down Expand Up @@ -58,3 +59,28 @@ func TestGetFloat(t *testing.T) {
})
})
}

func TestSerializeMeta(t *testing.T) {
Convey("Given an instance", t, func() {
instance := new(fargo.Instance)
Convey("With metadata", func() {
instance.SetMetadataString("test", "value")
Convey("Serializing results in correct JSON", func() {
b, err := instance.Metadata.MarshalJSON()
So(err, ShouldBeNil)
So(string(b), ShouldEqual, "{\"test\":\"value\"}")
})
Convey("Serializing results in correct XML", func() {
b, err := xml.Marshal(instance.Metadata)
So(err, ShouldBeNil)
So(string(b), ShouldEqual, "<InstanceMetadata><test>value</test></InstanceMetadata>")
})
Convey("Blank metadata results in blank XML", func() {
metadata := new(fargo.InstanceMetadata)
b, err := xml.Marshal(metadata)
So(err, ShouldBeNil)
So(string(b), ShouldEqual, "<InstanceMetadata></InstanceMetadata>")
})
})
})
}

0 comments on commit ae8b023

Please sign in to comment.