How to Generate UUID in Go

Go doesn't have a built-in UUID package, but github.com/google/uuid is the most popular choice for generating RFC 4122 compliant UUIDs.

1. Install the Package

go get github.com/google/uuid

2. Generate UUID v4 (Random)

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    // Generate a random UUID (version 4)
    id := uuid.New()
    fmt.Println(id)
    // Output: 550e8400-e29b-41d4-a716-446655440000

    // Get as string
    idString := id.String()
    fmt.Println(idString)
}

3. Generate UUID v5 (Name-based)

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    namespace := uuid.NameSpaceDNS
    name := "example.com"

    id := uuid.NewSHA1(namespace, []byte(name))
    fmt.Println(id)
    // Same name always produces the same UUID
}

4. Parse UUID from String

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    id, err := uuid.Parse("550e8400-e29b-41d4-a716-446655440000")
    if err != nil {
        fmt.Println("Invalid UUID:", err)
        return
    }
    fmt.Println(id)
}

5. UUID with GORM

package main

import (
    "github.com/google/uuid"
    "gorm.io/gorm"
)

type Product struct {
    ID    uuid.UUID `gorm:"type:uuid;primaryKey"`
    Name  string
    Price float64
}

func (p *Product) BeforeCreate(tx *gorm.DB) error {
    if p.ID == uuid.Nil {
        p.ID = uuid.New()
    }
    return nil
}

Ready to use what you learned?

Try UUID Generator now