Generate UUID in Go
Use github.com/google/uuid — the standard UUID library for Go. Covers v4, v7, GORM models, and HTTP handler patterns.
Need a UUID right now? Generate one instantly in your browser.
Open UUID v4 Generator →The Quick Answer
Go's standard library doesn't include a UUID package. Use github.com/google/uuid — the widely accepted community standard.
go get github.com/google/uuid
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
id := uuid.New() // UUID v4
fmt.Println(id.String())
// → "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// As string directly
idStr := uuid.NewString()
fmt.Println(idStr)
}
UUID v7 in Go (Time-Ordered)
UUID v7 is sortable by creation time and avoids B-tree fragmentation in databases. The google/uuid package supports it from v1.6+.
import "github.com/google/uuid"
id, err := uuid.NewV7()
if err != nil {
// error only if random source fails
panic(err)
}
fmt.Println(id.String())
// → "0190c0a7-73b7-7000-b7c8-4b4aabd7e00e"
// First segment is a millisecond timestamp — rows sort naturally.
GORM — UUID as Primary Key
package model
import (
"github.com/google/uuid"
"gorm.io/gorm"
)
type Product struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey"`
Name string `gorm:"not null"`
}
func (p *Product) BeforeCreate(tx *gorm.DB) error {
if p.ID == uuid.Nil {
p.ID = uuid.New()
}
return nil
}
HTTP Handler Pattern
package main
import (
"net/http"
"github.com/google/uuid"
)
func getItem(w http.ResponseWriter, r *http.Request) {
rawID := r.PathValue("id") // Go 1.22+ stdlib routing
id, err := uuid.Parse(rawID)
if err != nil {
http.Error(w, "invalid UUID", http.StatusBadRequest)
return
}
// id is now a validated uuid.UUID
_ = id
}
Frequently Asked Questions
What is the best UUID package for Go?
github.com/google/uuid is the de-facto standard. It is maintained by Google, widely used in production, and supports UUID v1, v4, v6, and v7. Install with: go get github.com/google/uuid
Is there a built-in UUID generator in Go's standard library?
No. Go's standard library does not include a UUID package. The crypto/rand package provides the underlying randomness but you still need to build or import the UUID format logic. Use github.com/google/uuid rather than rolling your own.
How do I use a UUID as a primary key in GORM?
Embed a uuid.UUID field with a BeforeCreate hook to auto-assign it. The google/uuid package's UUID type implements database/sql interfaces natively, so it works with GORM out of the box.
Should I use uuid.New() or uuid.NewString() in Go?
Use uuid.New() when you need the uuid.UUID type (e.g. to pass to a function, store in a struct, or use with GORM). Use uuid.NewString() when you only need the hyphenated string representation and want to skip the intermediate .String() call.