Is there a method to generate a UUID with go language

后端 未结 12 1715
温柔的废话
温柔的废话 2020-12-07 12:15

I have code that looks like this:

u := make([]byte, 16)
_, err := rand.Read(u)
if err != nil {
    return
}

u[8] = (u[8] | 0x80) & 0xBF // what does thi         


        
相关标签:
12条回答
  • 2020-12-07 12:41

    From Russ Cox's post:

    There's no official library. Ignoring error checking, this seems like it would work fine:

    f, _ := os.Open("/dev/urandom")
    b := make([]byte, 16)
    f.Read(b)
    f.Close()
    uuid := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
    

    Note: In the original, pre Go 1 version the first line was:

    f, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)
    

    Here it compiles and executes, only /dev/urandom returns all zeros in the playground. Should work fine locally.

    In the same thread there are some other methods/references/packages found.

    0 讨论(0)
  • 2020-12-07 12:43

    "crypto/rand" is cross platform pkg for random bytes generattion

    package main
    
    import (
        "crypto/rand"
        "fmt"
    )
    
    // Note - NOT RFC4122 compliant
    func pseudo_uuid() (uuid string) {
    
        b := make([]byte, 16)
        _, err := rand.Read(b)
        if err != nil {
            fmt.Println("Error: ", err)
            return
        }
    
        uuid = fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
    
        return
    }
    
    0 讨论(0)
  • 2020-12-07 12:44

    The go-uuid library is NOT RFC4122 compliant. The variant bits are not set correctly. There have been several attempts by community members to have this fixed but pull requests for the fix are not being accepted.

    You can generate UUIDs using the Go uuid library I rewrote based on the go-uuid library. There are several fixes and improvements. This can be installed with:

    go get github.com/twinj/uuid
    

    You can generate random (version 4) UUIDs with:

    import "github.com/twinj/uuid"
    
    u := uuid.NewV4()
    

    The returned UUID type is an interface and the underlying type is an array.

    The library also generates v1 UUIDs and correctly generates v3 and 5 UUIDs. There are several new methods to help with printing and formatting and also new general methods to create UUIDs based off of existing data.

    0 讨论(0)
  • 2020-12-07 12:44

    There is an official implementation by Google: https://github.com/google/uuid

    Generating a version 4 UUID works like this:

    package main
    
    import (
        "fmt"
        "github.com/google/uuid"
    )
    
    func main() {
        id := uuid.New()
        fmt.Println(id.String())
    }
    

    Try it here: https://play.golang.org/p/6YPi1djUMj9

    0 讨论(0)
  • 2020-12-07 12:48
    u[8] = (u[8] | 0x80) & 0xBF // what's the purpose ?
    u[6] = (u[6] | 0x40) & 0x4F // what's the purpose ?
    

    These lines clamp the values of byte 6 and 8 to a specific range. rand.Read returns random bytes in the range 0-255, which are not all valid values for a UUID. As far as I can tell, this should be done for all the values in the slice though.

    If you are on linux, you can alternatively call /usr/bin/uuidgen.

    package main
    
    import (
        "fmt"
        "log"
        "os/exec"
    )
    
    func main() {
        out, err := exec.Command("uuidgen").Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s", out)
    }
    

    Which yields:

    $ go run uuid.go 
    dc9076e9-2fda-4019-bd2c-900a8284b9c4
    
    0 讨论(0)
  • 2020-12-07 12:49

    The gorand package has a UUID method that returns a Version 4 (randomly generated) UUID in its canonical string representation ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") and it's RFC 4122 compliant.

    It also uses the crypto/rand package to ensure the most cryptographically secure generation of UUIDs across all platforms supported by Go.

    import "github.com/leonelquinteros/gorand"
    
    func main() {
        uuid, err := gorand.UUID()
        if err != nil {
            panic(err.Error())
        }
    
        println(uuid)
    } 
    
    0 讨论(0)
提交回复
热议问题