Browse Source

Merge pull request #125 from dpanth3r/master

Implement UnmarshalJSON for UUID
Ben Hood 11 năm trước cách đây
mục cha
commit
ccda481d83
3 tập tin đã thay đổi với 26 bổ sung1 xóa
  1. 1 0
      AUTHORS
  2. 15 0
      uuid.go
  3. 10 1
      uuid_test.go

+ 1 - 0
AUTHORS

@@ -19,3 +19,4 @@ Kasper Middelboe Petersen <me@phant.dk>
 Harpreet Sawhney <harpreet.sawhney@gmail.com>
 Charlie Andrews <charlieandrews.cwa@gmail.com>
 Stanislavs Koikovs <stanislavs.koikovs@gmail.com>
+Dan Forest <bonjour@dan.tf>

+ 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)
+	}
+
+	parsed, err := ParseUUID(str[1:37])
+	if err == nil {
+		copy(u[:], parsed[:])
+	}
+
+	return err
+}

+ 10 - 1
uuid_test.go

@@ -66,7 +66,16 @@ func TestPredefinedUUID(t *testing.T) {
 		}
 		expectedJson := `"` + testsUUID[i].input + `"`
 		if string(json) != expectedJson {
-			t.Errorf("MarshalJSON #%d: expected %d got %d", i, expectedJson, string(json))
+			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)
 		}
 	}
 }