home‎ > ‎go‎ > ‎

Go generate UUID

Here is a simple UUID generator, it uses version 4, Pseudo Random, as described in RFC 4122

uuid.go

package uuid

import (
"encoding/hex"
"crypto/rand"
)

func GenUUID() (string, error) {
uuid := make([]byte, 16)
n, err := rand.Read(uuid)
if n != len(uuid) || err != nil {
return "", err
}
// TODO: verify the two lines implement RFC 4122 correctly
uuid[8] = 0x80 // variant bits see page 5
uuid[4] = 0x40 // version 4 Pseudo Random, see page 7

return hex.EncodeToString(uuid), nil
}

uuid test & benchmark routine, uuid_test.go

package uuid

import (
 "testing"
 )

func TestUUID(t *testing.T) {
    uuid, err := GenUUID()
    if  err != nil {
        t.Fatalf("GenUUID error %s",err)
    }
    t.Logf("uuid[%s]\n",uuid)
}

func BenchmarkUUID(b *testing.B) {
    m := make(map[string]int,1000) 
    for i := 0; i < b.N; i++ {
       uuid, err := GenUUID()
       if  err != nil {
        b.Fatalf("GenUUID error %s",err)
       } 
       b.StopTimer()
       c := m[uuid]
       if c > 0 {
         b.Fatalf("duplicate uuid[%s] count %d",uuid,c )
       } 
       m[uuid] = c+1
       b.StartTimer()
    }
}

command to build uuid.go
go build  uuid.go

command to run test & benchmark:
go test -v -bench=".*UUID"  uuid.go uuid_test.go 

sample output (i5 Dell Latitude E6410 laptop, running Ubuntu 12.04)
=== RUN TestUUID
--- PASS: TestUUID (0.00 seconds)
uuid_test.go:13: uuid[50a4cca6402223f280541ed8135a08b9]
PASS
BenchmarkUUID 1000000      1914 ns/op
ok   command-line-arguments 2.982s

The source code of uuid.go and uuid_test.go are attached below.

ċ
uuid.go
(1k)
Ashish Banerjee,
May 12, 2012, 9:30 PM
ċ
uuid_test.go
(1k)
Ashish Banerjee,
May 12, 2012, 9:30 PM
Comments