mirror of
https://github.com/status-im/consul.git
synced 2025-02-03 09:24:25 +00:00
consul: Adding util method to generate a UUID
This commit is contained in:
parent
1e5c8a445c
commit
26ee0e3c76
@ -1,6 +1,7 @@
|
|||||||
package consul
|
package consul
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
crand "crypto/rand"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/hashicorp/serf/serf"
|
"github.com/hashicorp/serf/serf"
|
||||||
@ -160,3 +161,18 @@ func runtimeStats() map[string]string {
|
|||||||
"cpu_count": strconv.FormatInt(int64(runtime.NumCPU()), 10),
|
"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])
|
||||||
|
}
|
||||||
|
@ -2,6 +2,7 @@ package consul
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/hashicorp/serf/serf"
|
"github.com/hashicorp/serf/serf"
|
||||||
|
"regexp"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -75,3 +76,19 @@ func TestByteConversion(t *testing.T) {
|
|||||||
t.Fatalf("no match")
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user