Fragment Description:



Using a 'uuid' generator to create a unique identity.
Suggested by visitors of this site as an example usage of the 'crypto/rand' and 'encoding/hex' packages.
Specification mentioned here:
http://www.ietf.org/rfc/rfc4122.txt


uuidUniqueID

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:36

/* ... <== see fragment description ... */

package main

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

// newUUID generates a random UUID according to RFC 4122
//
func newUUID() (string, error) {
    uuid := make([]byte, 16)
    // "crypto/rand" provides the function Read
    n, err := rand.Read(uuid)
    // a more explicit way to write this line uses rand.Reader
    // Reader is a  global, shared instance of a cryptographically
    // strong pseudo-random generator.
    // io.ReadFull reads exactly len(buf) bytes from r into buf.
    // sign: func ReadFull(r Reader, buf []byte) (n int, err error)
    // The statement would be:
    // n, err := io.ReadFull(rand.Reader, uuid)
    //
    if n != len(uuid) || err != nil {
        return "", err
    }
    // variant bits; see section 4.1.1
    //
    uuid[8] = uuid[8]&^0xc0 | 0x80
    // version 4 (pseudo-random); see section 4.1.3
    //
    uuid[6] = uuid[6]&^0xf0 | 0x40
    fmt.Printf("check uuid:\t%s\n", hex.EncodeToString(uuid))
    return fmt.Sprintf("-----\nIDentifier:\t%x-%x-%x-%x-%x\n-----\n",
        uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil
}
func main() {
    uuid, err := newUUID()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(uuid)
}

/* Expected Output:
check uuid:    dccfabe17b474e7295aa047c9a2d6104
-----
IDentifier:    dccfabe1-7b47-4e72-95aa-047c9a2d6104
-----
*/



Comments