瀏覽代碼

uuid: implement text marshalling functions

fixes #562
Chris Bannister 10 年之前
父節點
當前提交
0d2d73e7ce
共有 2 個文件被更改,包括 30 次插入0 次删除
  1. 9 0
      uuid.go
  2. 21 0
      uuid_test.go

+ 9 - 0
uuid.go

@@ -240,3 +240,12 @@ func (u *UUID) UnmarshalJSON(data []byte) error {
 
 	return err
 }
+
+func (u UUID) MarshalText() ([]byte, error) {
+	return []byte(u.String()), nil
+}
+
+func (u *UUID) UnmarshalText(text []byte) (err error) {
+	*u, err = ParseUUID(string(text))
+	return
+}

+ 21 - 0
uuid_test.go

@@ -195,3 +195,24 @@ func TestUnmarshalJSON(t *testing.T) {
 	}
 
 }
+
+func TestMarshalText(t *testing.T) {
+	u, err := ParseUUID("486f3a88-775b-11e3-ae07-d231feb1dc81")
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	text, err := u.MarshalText()
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	var u2 UUID
+	if err := u2.UnmarshalText(text); err != nil {
+		t.Fatal(err)
+	}
+
+	if u != u2 {
+		t.Fatalf("uuids not equal after marshalling: before=%s after=%s", u, u2)
+	}
+}