Go Fiber is an Express-inspired HTTP framework built on Fasthttp — one of the fastest HTTP engines in the Go ecosystem. UUID v7 is the natural choice for Fiber APIs: it provides millisecond-precision time ordering for database primary keys and embeds request timing information in trace IDs. See UUID in Go for the google/uuid package overview.
Setup
go get github.com/gofiber/fiber/v2
go get github.com/google/uuid
go get gorm.io/gorm gorm.io/driver/postgres
Requires google/uuid v1.6+ for uuid.NewV7().
Trace ID middleware
package middleware
import (
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
// TraceID injects a UUID v7 trace ID into every request context.
// UUID v7's timestamp prefix encodes when the request arrived.
func TraceID() fiber.Handler {
return func(c *fiber.Ctx) error {
id, err := uuid.NewV7()
if err != nil {
return c.Status(fiber.StatusInternalServerError).SendString("trace ID generation failed")
}
traceID := id.String()
c.Locals("traceID", traceID)
c.Set("X-Trace-ID", traceID)
return c.Next()
}
}
// GetTraceID retrieves the trace ID from the request context.
func GetTraceID(c *fiber.Ctx) string {
if id, ok := c.Locals("traceID").(string); ok {
return id
}
return ""
}
GORM model with UUID v7 primary key
package model
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
type Order struct {
ID string `gorm:"type:varchar(36);primaryKey"`
CustomerID string `gorm:"type:varchar(36);not null;index"`
Total float64 `gorm:"not null"`
Status string `gorm:"default:'pending'"`
CreatedAt time.Time // redundant with UUID v7 — kept for ORM compatibility
}
// BeforeCreate generates a UUID v7 primary key before insertion.
func (o *Order) BeforeCreate(tx *gorm.DB) error {
if o.ID == "" {
id, err := uuid.NewV7()
if err != nil {
return err
}
o.ID = id.String()
}
return nil
}
Fiber route handlers
package handler
import (
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"gorm.io/gorm"
"yourapp/middleware"
"yourapp/model"
)
type OrderHandler struct {
db *gorm.DB
}
func NewOrderHandler(db *gorm.DB) *OrderHandler {
return &OrderHandler{db: db}
}
// POST /orders
func (h *OrderHandler) Create(c *fiber.Ctx) error {
var body struct {
CustomerID string `json:"customerId"`
Total float64 `json:"total"`
}
if err := c.BodyParser(&body); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid body"})
}
order := model.Order{
CustomerID: body.CustomerID,
Total: body.Total,
}
if err := h.db.Create(&order).Error; err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
}
return c.Status(fiber.StatusCreated).JSON(order)
}
// GET /orders — cursor pagination using UUID v7
func (h *OrderHandler) List(c *fiber.Ctx) error {
cursor := c.Query("cursor")
limit := 20
var orders []model.Order
query := h.db.Order("id ASC").Limit(limit)
if cursor != "" {
query = query.Where("id > ?", cursor)
}
if err := query.Find(&orders).Error; err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
}
var nextCursor *string
if len(orders) == limit {
last := orders[len(orders)-1].ID
nextCursor = &last
}
return c.JSON(fiber.Map{
"orders": orders,
"nextCursor": nextCursor,
"traceId": middleware.GetTraceID(c),
})
}
UUID v7 ORDER BY id ASC is lexicographically equivalent to chronological order — no secondary created_at index needed. See UUID v7 for Cursor Pagination.
App wiring with middleware
package main
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"yourapp/handler"
"yourapp/middleware"
"yourapp/model"
)
func main() {
dsn := "host=localhost user=postgres dbname=myapp sslmode=disable"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("failed to connect to database:", err)
}
db.AutoMigrate(&model.Order{})
app := fiber.New()
app.Use(recover.New())
app.Use(logger.New())
app.Use(middleware.TraceID()) // UUID v7 trace ID on every request
orders := handler.NewOrderHandler(db)
app.Post("/orders", orders.Create)
app.Get("/orders", orders.List)
log.Fatal(app.Listen(":3000"))
}
Idempotency with UUID v7
// POST /payments — UUID v7 idempotency key
func (h *PaymentHandler) Create(c *fiber.Ctx) error {
idempotencyKey := c.Get("Idempotency-Key")
if idempotencyKey == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "Idempotency-Key header required",
})
}
// Validate it's a UUID
if _, err := uuid.Parse(idempotencyKey); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "Idempotency-Key must be a valid UUID",
})
}
// Check for existing payment with this idempotency key
var existing model.Payment
if err := h.db.Where("idempotency_key = ?", idempotencyKey).First(&existing).Error; err == nil {
// Already processed — return the original response
return c.Status(fiber.StatusOK).JSON(existing)
}
// Process payment...
return c.Status(fiber.StatusCreated).JSON(fiber.Map{"id": idempotencyKey})
}
See UUID as Idempotency Keys for the full idempotency pattern.
Timestamp extraction from UUID v7 trace IDs
import (
"time"
"github.com/google/uuid"
)
// ExtractTimestamp extracts the creation time from a UUID v7 string.
func ExtractTimestamp(uuidStr string) (time.Time, error) {
id, err := uuid.Parse(uuidStr)
if err != nil {
return time.Time{}, err
}
ts, err := uuid.TimestampFromV7(id)
if err != nil {
return time.Time{}, err
}
t, _ := ts.Time()
return t, nil
}
// Usage: determine when a request was initiated from its trace ID alone
t, _ := ExtractTimestamp("018fbe3a-4c5d-7b12-8f3e-1a2b3c4d5e6f")
// t = the millisecond the UUID was generated
See UUID Bit Fields for the timestamp bit layout.
Further reading
- UUID in Go — google/uuid Package Guide
- UUID v7 in Microservices — Trace IDs and Correlation
- UUID v7 for Cursor Pagination
- UUID as Idempotency Keys
- UUID in Databases — Storage and Indexing
External references
Frequently asked questions
How do I generate UUID v7 in Go Fiber?
Use the google/uuid package: uuid.New() generates UUID v4; for v7 use uuid.NewV7() (available from v1.6+). In a Fiber handler, call id, _ := uuid.NewV7() and use id.String() as the primary key or trace ID. See UUID in Go for the full package guide.
Should I store UUID v7 as string or binary in Go Fiber with GORM?
Use string (VARCHAR(36)) for simplicity or []byte (BINARY(16)) for compact storage. GORM's type:uuid tag works with PostgreSQL's native UUID column. For MySQL use type:varchar(36). UUID v7 strings sort lexicographically in chronological order, so ORDER BY id gives insertion time order without a separate created_at column. See UUID in Databases.
How does UUID v7 work as a trace ID in Fiber middleware?
Generate a UUID v7 in a Fiber middleware and attach it to the request context: c.Locals("traceID", id.String()). Downstream handlers read it with c.Locals("traceID").(string). Set it on the response header with c.Set("X-Trace-ID", traceID) so clients can correlate requests. UUID v7's timestamp prefix lets you extract when the request arrived from the ID alone. See UUID v7 in Microservices.