瀏覽代碼

Merge pull request #173 from SilentCircle/master

Be more flexible in UUID JSON unmarshaling
Ben Hood 11 年之前
父節點
當前提交
fc14ae43d0
共有 3 個文件被更改,包括 25 次插入3 次删除
  1. 1 0
      AUTHORS
  2. 4 3
      uuid.go
  3. 20 0
      uuid_test.go

+ 1 - 0
AUTHORS

@@ -22,3 +22,4 @@ Stanislavs Koikovs <stanislavs.koikovs@gmail.com>
 Dan Forest <bonjour@dan.tf>
 Miguel Serrano <miguelvps@gmail.com>
 Stefan Radomski <gibheer@zero-knowledge.org>
+Josh Wright <jshwright@gmail.com>

+ 4 - 3
uuid.go

@@ -14,6 +14,7 @@ import (
 	"fmt"
 	"io"
 	"net"
+	"strings"
 	"sync/atomic"
 	"time"
 )
@@ -216,12 +217,12 @@ func (u UUID) MarshalJSON() ([]byte, error) {
 
 // Unmarshaling for JSON
 func (u *UUID) UnmarshalJSON(data []byte) error {
-	str := string(data)
-	if len(str) != 38 {
+	str := strings.Trim(string(data), `"`)
+	if len(str) > 36 {
 		return fmt.Errorf("invalid JSON UUID %s", str)
 	}
 
-	parsed, err := ParseUUID(str[1:37])
+	parsed, err := ParseUUID(str)
 	if err == nil {
 		copy(u[:], parsed[:])
 	}

+ 20 - 0
uuid_test.go

@@ -137,3 +137,23 @@ func TestTimeUUID(t *testing.T) {
 		timestamp = ts
 	}
 }
+
+func TestUnmarshalJSON(t *testing.T) {
+	var withHyphens, withoutHypens, tooLong UUID
+
+	withHyphens.UnmarshalJSON([]byte(`"486f3a88-775b-11e3-ae07-d231feb1dc81"`))
+	if withHyphens.Time().Truncate(time.Second) != time.Date(2014, 1, 7, 5, 19, 29, 0, time.UTC) {
+		t.Errorf("Expected date of 1/7/2014 at 5:19:29, got %v", withHyphens.Time())
+	}
+
+	withoutHypens.UnmarshalJSON([]byte(`"486f3a88775b11e3ae07d231feb1dc81"`))
+	if withoutHypens.Time().Truncate(time.Second) != time.Date(2014, 1, 7, 5, 19, 29, 0, time.UTC) {
+		t.Errorf("Expected date of 1/7/2014 at 5:19:29, got %v", withoutHypens.Time())
+	}
+
+	err := tooLong.UnmarshalJSON([]byte(`"486f3a88-775b-11e3-ae07-d231feb1dc81486f3a88"`))
+	if err == nil {
+		t.Errorf("no error for invalid JSON UUID")
+	}
+
+}