How to Generate UUID in Go (Golang)
- Go has no built-in UUID type — use the google/uuid package (most common) or build from crypto/rand.
- go get github.com/google/uuid — then uuid.New() generates a UUID v4.
- uuid.New().String() returns the standard 36-character hyphenated format.
- The google/uuid package is used by millions of Go projects and is effectively the standard.
- For databases, store as a string (VARCHAR/TEXT) or use a driver-specific UUID type.
Table of Contents
Go's standard library does not include a UUID type, but the google/uuid package is so widely adopted it is the effective standard — used by Kubernetes, Docker, and most major Go projects. This guide covers installation, generation, validation, and database patterns.
Install and Import google/uuid
go get github.com/google/uuid
Then in your code:
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
id := uuid.New()
fmt.Println(id)
// Output: 550e8400-e29b-41d4-a716-446655440000
// As a string:
idStr := uuid.New().String()
fmt.Println(idStr)
// "550e8400-e29b-41d4-a716-446655440000"
}
uuid.New() calls uuid.NewRandom() internally and panics if the random source fails (extremely rare). Use uuid.NewRandom() if you want to handle the error explicitly.
Error-Handled UUID Generation
// uuid.New() panics on failure — for production code handle the error:
id, err := uuid.NewRandom()
if err != nil {
return fmt.Errorf("failed to generate UUID: %w", err)
}
fmt.Println(id.String())
// UUID v4 from raw crypto/rand (no dependency):
import (
"crypto/rand"
"encoding/hex"
"fmt"
)
func generateUUIDv4() (string, error) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
return "", err
}
b[6] = (b[6] & 0x0f) | 0x40 // version 4
b[8] = (b[8] & 0x3f) | 0x80 // variant bits
return fmt.Sprintf("%x-%x-%x-%x-%x",
b[0:4], b[4:6], b[6:8], b[8:10], b[10:]), nil
}
The raw crypto/rand approach adds no dependencies but is more verbose. For most projects, google/uuid is cleaner and already present as a transitive dependency anyway.
UUID as a Struct Field in Go
import "github.com/google/uuid"
type Order struct {
ID uuid.UUID `json:"id"`
Status string `json:"status"`
}
// Create new order:
order := Order{
ID: uuid.New(),
Status: "pending",
}
// JSON marshaling/unmarshaling works automatically:
// uuid.UUID implements json.Marshaler and json.Unmarshaler
// JSON output: {"id":"550e8400-e29b-41d4-a716-446655440000","status":"pending"}
// Initialize from a known UUID string:
id, err := uuid.Parse("550e8400-e29b-41d4-a716-446655440000")
if err != nil {
log.Fatal(err)
}
order.ID = id
UUID in Go HTTP Handlers
import (
"net/http"
"github.com/google/uuid"
"github.com/go-chi/chi/v5" // or any router
)
func GetOrderHandler(w http.ResponseWriter, r *http.Request) {
idStr := chi.URLParam(r, "id")
id, err := uuid.Parse(idStr)
if err != nil {
http.Error(w, "Invalid order ID", http.StatusBadRequest)
return
}
order, err := orderService.GetByID(id)
if err != nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(order)
}
// Route registration:
r.Get("/orders/{id}", GetOrderHandler)
Always use uuid.Parse() to validate the incoming string before using it — do not pass raw path strings to your database queries.
UUID in GORM and Database Storage
import (
"gorm.io/gorm"
"github.com/google/uuid"
)
type Order struct {
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
Status string
CreatedAt time.Time
}
// Auto-generate UUID before create:
func (o *Order) BeforeCreate(tx *gorm.DB) error {
if o.ID == uuid.Nil {
o.ID = uuid.New()
}
return nil
}
// PostgreSQL: gen_random_uuid() generates UUID at the DB level
// MySQL: no native UUID type — use type:varchar(36) or type:binary(16)
For PostgreSQL, letting the database generate the UUID with gen_random_uuid() is the most reliable approach — it works even when records are inserted outside of your Go application.
Need a UUID for Go Testing?
Generate RFC-compliant UUID v4 values in one click — paste into Go test fixtures, seed files, or config values without spinning up your app.
Open Free UUID GeneratorFrequently Asked Questions
Does Go have a built-in UUID package?
No. Go's standard library does not include a UUID type. The google/uuid package (github.com/google/uuid) is the de facto standard — it is used by Kubernetes, Docker, and most major Go projects.
What is the difference between uuid.New() and uuid.NewRandom() in Go?
uuid.New() wraps uuid.NewRandom() and panics if the random source fails. uuid.NewRandom() returns (UUID, error) so you can handle the failure — preferred for production code where you want explicit error handling.
How do I store UUID in a Go database with PostgreSQL?
Use the pgx driver with its native UUID support, or store as a string with VARCHAR/TEXT. With GORM, declare the field as uuid.UUID with gorm:"type:uuid" and use BeforeCreate to auto-generate.
How do I compare two UUIDs in Go?
uuid.UUID is a [16]byte array — use id1 == id2 for direct comparison (works because arrays are comparable in Go). Or use id1.String() == id2.String() if one is a string.
Is google/uuid thread-safe in Go?
Yes. uuid.New() uses crypto/rand which is goroutine-safe. You can call uuid.New() concurrently from multiple goroutines without synchronization.

