Go has no UUID type in its standard library, so most projects use the widely trusted google/uuid package. It generates UUID v4 and, in recent versions, UUID v7, and it parses and validates strings cleanly.
Key takeaways
- Use github.com/google/uuid for generation and parsing.
- uuid.NewString() gives a random v4; NewV7() gives a time-ordered v7.
- Parse untrusted input with uuid.Parse and handle the error.
Generate a UUID in Go
Install the package with go get github.com/google/uuid, then generate a random v4 or a time-ordered v7. NewString returns the canonical lowercase string directly.
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
v4 := uuid.NewString() // random UUID v4
v7, _ := uuid.NewV7() // time-ordered UUID v7 (google/uuid v1.6+)
fmt.Println(v4)
fmt.Println(v7.String())
}Parse and validate
Validate incoming identifiers by parsing them. uuid.Parse accepts hyphenated, URN and braced forms and returns an error for anything invalid, which is safer than a hand-written check.
id, err := uuid.Parse(input)
if err != nil {
// reject invalid UUID
}
_ = id