فهرست منبع

Let UUID implement Unmarshaling interface for encoding/json

Dan Forest 11 سال پیش
والد
کامیت
39d8f13896
2فایلهای تغییر یافته به همراه24 افزوده شده و 0 حذف شده
  1. 15 0
      uuid.go
  2. 9 0
      uuid_test.go

+ 15 - 0
uuid.go

@@ -213,3 +213,18 @@ func (u UUID) Time() time.Time {
 func (u UUID) MarshalJSON() ([]byte, error) {
 	return []byte(`"` + u.String() + `"`), nil
 }
+
+// Unmarshaling for JSON
+func (u *UUID) UnmarshalJSON(data []byte) error {
+	str := string(data)
+	if len(str) != 38 {
+		return fmt.Errorf("invalid JSON UUID %s", str)
+	}
+
+	newU, err := ParseUUID(str[1:37])
+	if err == nil {
+		copy(u[:], newU[:])
+	}
+
+	return err
+}

+ 9 - 0
uuid_test.go

@@ -68,6 +68,15 @@ func TestPredefinedUUID(t *testing.T) {
 		if string(json) != expectedJson {
 			t.Errorf("MarshalJSON #%d: expected %v got %v", i, expectedJson, string(json))
 		}
+
+		var unmarshaled UUID
+		err = unmarshaled.UnmarshalJSON(json)
+		if err != nil {
+			t.Errorf("UnmarshalJSON #%d: %v", i, err)
+		}
+		if unmarshaled != uuid {
+			t.Errorf("UnmarshalJSON #%d: expected %v got %v", i, uuid, unmarshaled)
+		}
 	}
 }