How to Generate a UUID in Go
Created
Modified
Using uuid Package
install
Use the following command to download the repository to the local file system.
install
go mod tidy
go get github.com/google/uuid
go install github.com/google/uuid
Note that since Go 1.17 installing packages with go get is deprecated:
uuid Usage
The uuid package generates and inspects UUIDs based on RFC 4122 and DCE 1.1: Authentication and Security Services.
See the following example:
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
u := uuid.New()
fmt.Println(u.String())
}
69b03ce1-ad12-4c98-a66d-861cc240f382
Using uuidgen Command
If you are on linux or mac, you can alternatively call /usr/bin/uuidgen
.
The uuidgen program creates (and prints) a new universally unique identifier (UUID) using the libuuid(3) library.
For example,
package main
import (
"fmt"
"os/exec"
)
func main() {
o, err := exec.Command("uuidgen").Output()
if err != nil {
// panic()
}
fmt.Printf("%s\n", o)
}
7b8cc5a3-f183-44b1-acb7-217eca047d43
Using uuid File
On Linux, you can read from /proc/sys/kernel/random/uuid:
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, _ := ioutil.ReadFile("/proc/sys/kernel/random/uuid")
fmt.Println(string(b))
}
051c9f24-afac-4d53-8aa5-64602a6c89bb
Using crypto Package
crypto/rand pkg implements a cryptographically secure random number generator. This doesn't comply to any standard 2.
Note: NOT RFC4122 compliant.
package main
import (
"crypto/rand"
"fmt"
)
// Note - NOT RFC4122 compliant
func uuid() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
// panic()
return ""
}
return fmt.Sprintf("%04x-%04x-%04x-%04x-%04x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}
func main() {
s := uuid()
fmt.Println(s)
}
043ca19e-a8e7-b0f5-070f-8d7dbb240a19