~samwhited/xmpp

9fc8054fe2c7545f664f27e9fa8d1f2e4a740ca2 — Sam Whited 5 years ago 9dd8a30
internal: Unmarshal JSON or XML host-meta files
2 files changed, 52 insertions(+), 6 deletions(-)

M internal/lookup.go
M internal/lookup_test.go
M internal/lookup.go => internal/lookup.go +20 -2
@@ 19,12 19,30 @@ import (
//         href="wss://web.example.com:443/ws" />
//   …
// </XRD>
//
// or
//
// {
//   …
//   "links": [
//     …
//     {
//       "rel": "urn:xmpp:alt-connections:xbosh",
//       "href": "https://web.example.com:5280/bosh"
//     },
//     {
//       "rel": "urn:xmpp:alt-connections:websocket",
//       "href": "wss://web.example.com:443/ws"
//     },
//     …
//   ]
// }
type XRD struct {
	XMLName xml.Name `xml:"http://docs.oasis-open.org/ns/xri/xrd-1.0 XRD"`
	Links   []Link   `xml:"Link"`
}

type Link struct {
	Rel  string `xml:"rel,attr"`
	Href string `xml:"href,attr"`
	Rel  string `xml:"rel,attr",json:"rel"`
	Href string `xml:"href,attr",json:"href"`
}

M internal/lookup_test.go => internal/lookup_test.go +32 -4
@@ 5,6 5,7 @@
package internal

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


@@ 14,7 15,7 @@ var (
	wsLink   = Link{Rel: "urn:xmpp:alt-connections:websocket", Href: "wss://web.example.com:443/ws"}
)

func TestUnmarshalWellKnown(t *testing.T) {
func TestUnmarshalWellKnownXML(t *testing.T) {
	hostMeta := []byte(`<XRD xmlns='http://docs.oasis-open.org/ns/xri/xrd-1.0'>
  <Link rel="urn:xmpp:alt-connections:xbosh"
        href="https://web.example.com:5280/bosh" />


@@ 27,10 28,37 @@ func TestUnmarshalWellKnown(t *testing.T) {
	}
	switch {
	case len(xrd.Links) != 2:
		t.Fatalf("internal: Expected 2 links in xrd unmarshal output, but found %d", len(xrd.Links))
		t.Fatalf("Expected 2 links in xrd unmarshal output, but found %d", len(xrd.Links))
	case xrd.Links[0] != boshLink:
		t.Fatalf("internal: Expected %v, but got %v", boshLink, xrd.Links[0])
		t.Fatalf("Expected %v, but got %v", boshLink, xrd.Links[0])
	case xrd.Links[1] != wsLink:
		t.Fatalf("internal: Expected %v, but got %v", wsLink, xrd.Links[1])
		t.Fatalf("Expected %v, but got %v", wsLink, xrd.Links[1])
	}
}

func TestUnmarshalWellKnownJSON(t *testing.T) {
	hostMeta := []byte(`{
  "links": [
    {
      "rel": "urn:xmpp:alt-connections:xbosh",
      "href": "https://web.example.com:5280/bosh"
    },
    {
      "rel": "urn:xmpp:alt-connections:websocket",
      "href": "wss://web.example.com:443/ws"
    }
  ]
}`)
	var xrd XRD
	if err := json.Unmarshal(hostMeta, &xrd); err != nil {
		t.Fatal(err)
	}
	switch {
	case len(xrd.Links) != 2:
		t.Fatalf("Expected 2 links in xrd unmarshal output, but found %d", len(xrd.Links))
	case xrd.Links[0] != boshLink:
		t.Fatalf("Expected %v, but got %v", boshLink, xrd.Links[0])
	case xrd.Links[1] != wsLink:
		t.Fatalf("Expected %v, but got %v", wsLink, xrd.Links[1])
	}
}