Bläddra i källkod

Port over uuid from Vault's helpers.

Jeff Mitchell 10 år sedan
förälder
incheckning
2951e8b970
3 ändrade filer med 50 tillägg och 1 borttagningar
  1. 7 1
      README.md
  2. 21 0
      uuid.go
  3. 22 0
      uuid_test.go

+ 7 - 1
README.md

@@ -1,2 +1,8 @@
 # uuid
-Generates UUID-format strings using purely high quality random bytes
+
+Generates UUID-format strings using purely high quality random bytes.
+
+Documentation
+=============
+
+The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/uuid).

+ 21 - 0
uuid.go

@@ -0,0 +1,21 @@
+package uuid
+
+import (
+	"crypto/rand"
+	"fmt"
+)
+
+// GenerateUUID is used to generate a random UUID
+func GenerateUUID() string {
+	buf := make([]byte, 16)
+	if _, err := rand.Read(buf); err != nil {
+		panic(fmt.Errorf("failed to read random bytes: %v", err))
+	}
+
+	return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
+		buf[0:4],
+		buf[4:6],
+		buf[6:8],
+		buf[8:10],
+		buf[10:16])
+}

+ 22 - 0
uuid_test.go

@@ -0,0 +1,22 @@
+package uuid
+
+import (
+	"regexp"
+	"testing"
+)
+
+func TestGenerateUUID(t *testing.T) {
+	prev := GenerateUUID()
+	for i := 0; i < 100; i++ {
+		id := GenerateUUID()
+		if prev == id {
+			t.Fatalf("Should get a new ID!")
+		}
+
+		matched, err := regexp.MatchString(
+			"[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}", id)
+		if !matched || err != nil {
+			t.Fatalf("expected match %s %v %s", id, matched, err)
+		}
+	}
+}