
8. Complete Code Examples
Example 1 - Complete Order Management System with Audit
// main.go
package main
import (
"log"
"github.com/gin-gonic/gin"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func main() {
// Database connection
dsn := "host=localhost user=postgres password=postgres dbname=orders port=5432"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
// Auto-migrate tables
db.AutoMigrate(
&Order{},
&OrderStateHistory{},
&StateTransition{},
&AuditLog{},
&APIAuditLog{},
)
// Seed valid state transitions
seedStateTransitions(db)
// Register audit callbacks
RegisterAuditCallbacks(db)
// Initialize repositories
auditRepo := NewAuditRepository(db)
orderRepo := NewOrderRepository(db, auditRepo)
// Initialize state machine
stateMachine := NewOrderStateMachine(db)
// Initialize services
orderService := NewOrderService(orderRepo, stateMachine)
// Setup router
router := gin.Default()
// Global middleware
router.Use(APIAuditMiddleware(db))
router.Use(AuthMiddleware()) // Your auth middleware
// Routes
v1 := router.Group("/api/v1")
{
orders := v1.Group("/orders")
{
orders.POST("", orderService.CreateOrder)
orders.GET("/:id", orderService.GetOrder)
orders.PUT("/:id", orderService.UpdateOrder)
orders.DELETE("/:id", orderService.DeleteOrder)
orders.POST("/:id/transition", orderService.TransitionState)
orders.GET("/:id/history", orderService.GetStateHistory)
}
}
log.Fatal(router.Run(":8080"))
}
func seedStateTransitions(db *gorm.DB) {
transitions := []StateTransition{
{FromState: "created", ToState: "payment_pending"},
{FromState: "payment_pending", ToState: "paid"},
{FromState: "payment_pending", ToState: "cancelled"},
{FromState: "paid", ToState: "processing"},
{FromState: "processing", ToState: "shipped"},
{FromState: "shipped", ToState: "delivered"},
{FromState: "delivered", ToState: "completed"},
{FromState: "paid", ToState: "refunded"},
{FromState: "processing", ToState: "cancelled"},
}
for _, t := range transitions {
db.FirstOrCreate(&t, t)
}
}Example 2 - Service Layer with Context Propagation
// service/order_service.go
package service
import (
"context"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
type OrderService struct {
orderRepo OrderRepository
stateMachine *OrderStateMachine
}
func NewOrderService(orderRepo OrderRepository, stateMachine *OrderStateMachine) *OrderService {
return &OrderService{
orderRepo: orderRepo,
stateMachine: stateMachine,
}
}
type CreateOrderRequest struct {
CustomerID uint `json:"customer_id" binding:"required"`
TotalAmount float64 `json:"total_amount" binding:"required"`
}
func (s *OrderService) CreateOrder(c *gin.Context) {
var req CreateOrderRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Build context with audit information
ctx := buildAuditContext(c)
// Generate order number
orderNumber := fmt.Sprintf("ORD-%d", time.Now().Unix())
order := &Order{
OrderNumber: orderNumber,
CustomerID: req.CustomerID,
TotalAmount: req.TotalAmount,
Status: string(StateCreated),
}
if err := s.orderRepo.Create(ctx, order); err != nil {
log.Printf("Failed to create order: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create order"})
return
}
c.JSON(http.StatusCreated, order)
}
func (s *OrderService) TransitionState(c *gin.Context) {
orderID := c.Param("id")
var req struct {
ToState string `json:"to_state" binding:"required"`
Reason string `json:"reason"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ctx := buildAuditContext(c)
userID := c.GetString("user_id")
id, _ := strconv.ParseUint(orderID, 10, 64)
err := s.stateMachine.TransitionTo(
ctx,
uint(id),
OrderState(req.ToState),
userID,
req.Reason,
)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "State transitioned successfully"})
}
func (s *OrderService) GetStateHistory(c *gin.Context) {
orderID := c.Param("id")
id, _ := strconv.ParseUint(orderID, 10, 64)
ctx := buildAuditContext(c)
history, err := s.stateMachine.GetStateHistory(ctx, uint(id))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get history"})
return
}
c.JSON(http.StatusOK, history)
}
// buildAuditContext extracts audit info from request and builds context
func buildAuditContext(c *gin.Context) context.Context {
ctx := c.Request.Context()
// Add audit fields to context
ctx = context.WithValue(ctx, "user_id", c.GetString("user_id"))
ctx = context.WithValue(ctx, "session_id", c.GetString("session_id"))
ctx = context.WithValue(ctx, "ip_address", c.ClientIP())
ctx = context.WithValue(ctx, "user_agent", c.Request.UserAgent())
ctx = context.WithValue(ctx, "request_id", c.GetHeader("X-Request-ID"))
return ctx
}Example 3 - Querying Audit Logs
// repository/audit_repository.go
package repository
import (
"context"
"encoding/json"
"time"
"gorm.io/gorm"
)
type AuditRepository interface {
Log(ctx context.Context, entry AuditEntry) error
GetByRecordID(ctx context.Context, tableName, recordID string) ([]AuditLog, error)
GetByUser(ctx context.Context, userID string, limit int) ([]AuditLog, error)
GetByDateRange(ctx context.Context, start, end time.Time) ([]AuditLog, error)
GetByOperation(ctx context.Context, operation string, limit int) ([]AuditLog, error)
}
type auditRepository struct {
db *gorm.DB
}
func NewAuditRepository(db *gorm.DB) AuditRepository {
return &auditRepository{db: db}
}
type AuditEntry struct {
TableName string
RecordID string
Operation string
OldValue json.RawMessage
NewValue json.RawMessage
}
func (r *auditRepository) Log(ctx context.Context, entry AuditEntry) error {
auditLog := AuditLog{
TableName: entry.TableName,
RecordID: entry.RecordID,
Operation: entry.Operation,
OldValue: entry.OldValue,
NewValue: entry.NewValue,
ChangedBy: getFromContext(ctx, "user_id"),
ChangedAt: time.Now(),
IPAddress: getFromContext(ctx, "ip_address"),
UserAgent: getFromContext(ctx, "user_agent"),
SessionID: getFromContext(ctx, "session_id"),
RequestID: getFromContext(ctx, "request_id"),
}
return r.db.WithContext(ctx).Create(&auditLog).Error
}
func (r *auditRepository) GetByRecordID(ctx context.Context, tableName, recordID string) ([]AuditLog, error) {
var logs []AuditLog
err := r.db.WithContext(ctx).
Where("table_name = ? AND record_id = ?", tableName, recordID).
Order("changed_at DESC").
Find(&logs).Error
return logs, err
}
func (r *auditRepository) GetByUser(ctx context.Context, userID string, limit int) ([]AuditLog, error) {
var logs []AuditLog
err := r.db.WithContext(ctx).
Where("changed_by = ?", userID).
Order("changed_at DESC").
Limit(limit).
Find(&logs).Error
return logs, err
}
func (r *auditRepository) GetByDateRange(ctx context.Context, start, end time.Time) ([]AuditLog, error) {
var logs []AuditLog
err := r.db.WithContext(ctx).
Where("changed_at BETWEEN ? AND ?", start, end).
Order("changed_at DESC").
Find(&logs).Error
return logs, err
}
func (r *auditRepository) GetByOperation(ctx context.Context, operation string, limit int) ([]AuditLog, error) {
var logs []AuditLog
err := r.db.WithContext(ctx).
Where("operation = ?", operation).
Order("changed_at DESC").
Limit(limit).
Find(&logs).Error
return logs, err
}9. Summary & Best Practices
Key Takeaways
Choose the Right Pattern
- Simple audit: Row versioning or shadow tables
- Complex domains: Event sourcing
- API tracking: Middleware-based logging
GORM Integration
- Use callbacks for automatic logging
- Leverage context for audit metadata
- Implement repository pattern for clean separation
State Management
- Use state machines for complex workflows
- Enforce valid transitions at database level
- Maintain complete history with sort keys
API Audit Logging
- Log asynchronously to avoid blocking
- Sanitize sensitive data
- Use correlation IDs for distributed tracing
Performance
- Index strategically (user_id, timestamp, table_name)
- Partition large tables by date
- Archive old logs to cold storage
- Use JSONB for flexible metadata
Compliance
- Encrypt sensitive audit data
- Implement log retention policies
- Support right-to-erasure (GDPR)
- Make logs tamper-proof (write-once)
Testing
- Unit test state transitions
- Integration test audit log creation
- Verify sensitive data is sanitized
- Test concurrent state changes
Making the Audit Insert Part of the Commit
The core transaction rule is simple: use the transaction handle for the content write and the audit insert and return every write error from the transaction callback. GORM commits when the callback returns nil; it rolls back when the callback returns an error. Calling the outer db handle for one of those writes would place that operation outside the transaction.
In this API, the application performs validation and version checks, the PostgreSQL repository writes a revision and updates the current pointer, then the same transaction-scoped repository inserts the audit row. The transaction also holds the editorial advisory lock. The lock coordinates concurrent editorial writers; the transaction makes the set of database changes atomic. Those are related but distinct responsibilities.
For a new request-aware GORM path, attach the request context before opening the transaction, for example db.WithContext(ctx).Transaction(...). GORM exposes that context to operations and hooks. The current editorial workflow does not pass a request context through this repository path, so this snippet describes a supported extension point, not current behavior.
References: GORM transactions, GORM context, Go transaction guidance.
Expanded from the supplied audit-log article
Should audit logging be asynchronous?
Asynchronous writes can improve request latency, but they introduce a reliability problem if the application treats a background task as the only copy of a required audit event.

The unsafe path commits first and records evidence later. The safer pattern uses a durable outbox.
There are two different cases:
Case A: The audit row lives in the same PostgreSQL database. Write it in the same transaction as the business change. This is the simplest reliable design for many APIs.
Case B: The audit record must be shipped to another service. Write a durable outbox event in the same transaction as the business change, then let a worker deliver it to the external sink. The worker must retry failures and handle duplicate delivery idempotently. The external copy may arrive later, so monitoring delivery lag is important.
The transactional outbox is not a reason to add a queue to every project. It solves a specific dual-write problem. If RefactorRoom only needs a local PostgreSQL audit table today, a normal transaction is easier to operate.
What I would implement first for RefactorRoom
The most useful starting point is not a large observability platform. It is a small set of reliable invariants:
- Every successful content edit creates a revision and an audit record in the same transaction.
- Every approval changes the approved revision pointer through an authorized operation and records an approval event.
- Audit records always include an authenticated actor, stable resource ID, action name and event time.
- Audit records avoid full content payloads when revision IDs provide enough context.
- Tests prove that an audit insert failure rolls back the content mutation.
- An editor can inspect revision history, while authorized operators can inspect the audit trail.
Later, when there is a real need, add event delivery, independent archiving, stronger integrity checks and database partitioning.
The main design lesson is straightforward: audit logging records the operation; revision history records the content. Treat them as complementary evidence, not as the same table under different names.
Further reading
Originally published on DEV Community.


