Made JID implement flag.Value.
authorChris Jones <chris@cjones.org>
Sat, 24 Dec 2011 11:05:54 -0700
changeset 3 6121aa2f21b1
parent 2 4dabfef08c8c
child 4 a8fbec71a194
Made JID implement flag.Value.
structs.go
structs_test.go
--- a/structs.go	Sat Dec 24 09:55:26 2011 -0700
+++ b/structs.go	Sat Dec 24 11:05:54 2011 -0700
@@ -8,9 +8,11 @@
 
 import (
 	"bytes"
+	"flag"
 	"fmt"
 	"io"
 	"os"
+	"regexp"
 	"xml"
 )
 
@@ -31,6 +33,7 @@
 	Resource *string
 }
 var _ fmt.Stringer = &JID{}
+var _ flag.Value = &JID{}
 
 // XMPP's <stream:stream> XML element
 type Stream struct {
@@ -70,6 +73,26 @@
 	return result
 }
 
+func (jid *JID) Set(val string) bool {
+	r := regexp.MustCompile("^(([^@/]+)@)?([^@/]+)(/([^@/]+))?$")
+	parts := r.FindStringSubmatch(val)
+	if parts == nil {
+		return false
+	}
+	if parts[2] == "" {
+		jid.Node = nil
+	} else {
+		jid.Node = &parts[2]
+	}
+	jid.Domain = parts[3]
+	if parts[5] == "" {
+		jid.Resource = nil
+	} else {
+		jid.Resource = &parts[5]
+	}
+	return true
+}
+
 func (s *Stream) MarshalXML() ([]byte, os.Error) {
 	buf := bytes.NewBuffer(nil)
 	buf.WriteString("<stream:stream")
--- a/structs_test.go	Sat Dec 24 09:55:26 2011 -0700
+++ b/structs_test.go	Sat Dec 24 11:05:54 2011 -0700
@@ -10,6 +10,45 @@
 	"xml"
 )
 
+func assertEquals(t *testing.T, expected, observed string) {
+	if expected != observed {
+		t.Errorf("Expected:\n%s\nObserved:\n%s\n", expected,
+			observed)
+	}
+}
+
+func TestJid(t *testing.T) {
+	str := "user@domain/res"
+	jid := &JID{}
+	if !jid.Set(str) {
+		t.Errorf("Set(%s) failed\n", str)
+	}
+	assertEquals(t, "user", *jid.Node)
+	assertEquals(t, "domain", jid.Domain)
+	assertEquals(t, "res", *jid.Resource)
+	assertEquals(t, str, jid.String())
+
+	str = "domain.tld"
+	if !jid.Set(str) {
+		t.Errorf("Set(%s) failed\n", str)
+	}
+	if jid.Node != nil {
+		t.Errorf("Node: %v\n", *jid.Node)
+	}
+	assertEquals(t, "domain.tld", jid.Domain)
+	if jid.Resource != nil {
+		t.Errorf("Resource: %v\n", *jid.Resource)
+	}
+	assertEquals(t, str, jid.String())
+}
+
+func assertMarshal(t *testing.T, expected string, marshal interface{}) {
+	buf := bytes.NewBuffer(nil)
+	xml.Marshal(buf, marshal)
+	observed := string(buf.Bytes())
+	assertEquals(t, expected, observed)
+}
+
 func TestStreamMarshal(t *testing.T) {
 	s := &Stream{to: "bob"}
 	exp := `<stream:stream to="bob">`
@@ -38,13 +77,3 @@
 		`" xml:lang="pt">things happen</text></stream:error>`
 	assertMarshal(t, exp, e)
 }
-
-func assertMarshal(t *testing.T, expected string, marshal interface{}) {
-	buf := bytes.NewBuffer(nil)
-	xml.Marshal(buf, marshal)
-	observed := string(buf.Bytes())
-	if expected != observed {
-		t.Errorf("Expected:\n%s\nObserved:\n%s\n", expected,
-			observed)
-	}
-}