consul: Adding util method to generate a UUID

This commit is contained in:
Armon Dadgar 2014-05-08 16:31:03 -07:00
parent a5c60eb556
commit 00477dca21
2 changed files with 33 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package consul
import (
crand "crypto/rand"
"encoding/binary"
"fmt"
"github.com/hashicorp/serf/serf"
@ -160,3 +161,18 @@ func runtimeStats() map[string]string {
"cpu_count": strconv.FormatInt(int64(runtime.NumCPU()), 10),
}
}
// generateUUID is used to generate a random UUID
func generateUUID() string {
buf := make([]byte, 16)
if _, err := crand.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])
}

View File

@ -2,6 +2,7 @@ package consul
import (
"github.com/hashicorp/serf/serf"
"regexp"
"testing"
)
@ -75,3 +76,19 @@ func TestByteConversion(t *testing.T) {
t.Fatalf("no match")
}
}
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)
}
}
}