
7. Go/PostgreSQL/GORM Implementation Patterns
Architecture Overview
┌─────────────────────────────────────────┐
│ HTTP Handler Layer │
│ (Middleware: Context, Auth, Logging) │
└──────────────┬──────────────────────────┘
│
┌──────────────▼──────────────────────────┐
│ Service Layer │
│ (Business Logic, Validation) │
└──────────────┬──────────────────────────┘
│
┌──────────────▼──────────────────────────┐
│ Repository Layer │
│ (Data Access, GORM Operations) │
└──────────────┬──────────────────────────┘
│
┌──────────────▼──────────────────────────┐
│ Database Layer │
│ (PostgreSQL + Audit Tables) │
└─────────────────────────────────────────┘Pattern 1 - GORM Callbacks for Automatic Audit Logging
Concept: Use GORM's hook system to automatically log changes
package models
import (
"context"
"encoding/json"
"time"
"gorm.io/gorm"
)
// AuditLog represents the audit log table
type AuditLog struct {
ID uint `gorm:"primaryKey"`
TableName string `gorm:"index;not null"`
RecordID string `gorm:"index;not null"`
Operation string `gorm:"index;not null"` // CREATE, UPDATE, DELETE, READ
OldValue json.RawMessage `gorm:"type:jsonb"`
NewValue json.RawMessage `gorm:"type:jsonb"`
ChangedBy string `gorm:"index"`
ChangedAt time.Time `gorm:"index;not null"`
IPAddress string
UserAgent string
SessionID string `gorm:"index"`
RequestID string `gorm:"index"`
Metadata json.RawMessage `gorm:"type:jsonb"`
}
// Auditable interface for models that support audit logging
type Auditable interface {
TableName() string
GetID() string
}
// Order model with audit support
type Order struct {
ID uint `gorm:"primaryKey"`
OrderNumber string `gorm:"uniqueIndex;not null"`
CustomerID uint `gorm:"not null"`
TotalAmount float64
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
func (Order) TableName() string {
return "orders"
}
func (o Order) GetID() string {
return fmt.Sprintf("%d", o.ID)
}
// RegisterAuditCallbacks registers GORM callbacks for audit logging
func RegisterAuditCallbacks(db *gorm.DB) {
// After Create
db.Callback().Create().After("gorm:after_create").Register("audit:after_create", func(db *gorm.DB) {
if db.Statement.Schema == nil {
return
}
// Check if model implements Auditable
if auditable, ok := db.Statement.Dest.(Auditable); ok {
createAuditLog(db, auditable, "CREATE", nil, db.Statement.Dest)
}
})
// After Update
db.Callback().Update().After("gorm:after_update").Register("audit:after_update", func(db *gorm.DB) {
if db.Statement.Schema == nil {
return
}
// Get old values before update (stored in context)
oldValue := db.Statement.Context.Value("audit:old_value")
if auditable, ok := db.Statement.Dest.(Auditable); ok {
createAuditLog(db, auditable, "UPDATE", oldValue, db.Statement.Dest)
}
})
// Before Update - capture old values
db.Callback().Update().Before("gorm:before_update").Register("audit:before_update", func(db *gorm.DB) {
if db.Statement.Schema == nil {
return
}
// Fetch current values
if auditable, ok := db.Statement.Dest.(Auditable); ok {
var oldModel interface{}
// Clone the model
db.Session(&gorm.Session{}).
Where(db.Statement.Schema.PrioritizedPrimaryField.Name+" = ?", auditable.GetID()).
First(&oldModel)
// Store in context for after_update
ctx := context.WithValue(db.Statement.Context, "audit:old_value", oldModel)
db.Statement.Context = ctx
}
})
// After Delete
db.Callback().Delete().After("gorm:after_delete").Register("audit:after_delete", func(db *gorm.DB) {
if db.Statement.Schema == nil {
return
}
if auditable, ok := db.Statement.Dest.(Auditable); ok {
createAuditLog(db, auditable, "DELETE", db.Statement.Dest, nil)
}
})
}
func createAuditLog(db *gorm.DB, auditable Auditable, operation string, oldValue, newValue interface{}) {
// Get audit context from request context
ctx := db.Statement.Context
var oldJSON, newJSON json.RawMessage
if oldValue != nil {
oldJSON, _ = json.Marshal(oldValue)
}
if newValue != nil {
newJSON, _ = json.Marshal(newValue)
}
auditLog := AuditLog{
TableName: auditable.TableName(),
RecordID: auditable.GetID(),
Operation: operation,
OldValue: oldJSON,
NewValue: newJSON,
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"),
}
// Use a new session to avoid triggering callbacks recursively
db.Session(&gorm.Session{SkipHooks: true}).Create(&auditLog)
}
func getFromContext(ctx context.Context, key string) string {
if val := ctx.Value(key); val != nil {
if str, ok := val.(string); ok {
return str
}
}
return ""
}Pattern 2 - Repository Pattern with Explicit Audit Logging
Concept: Repository layer explicitly logs changes
package repository
import (
"context"
"encoding/json"
"fmt"
"time"
"gorm.io/gorm"
)
// OrderRepository handles order data access
type OrderRepository interface {
Create(ctx context.Context, order *Order) error
Update(ctx context.Context, order *Order) error
Delete(ctx context.Context, id uint) error
FindByID(ctx context.Context, id uint) (*Order, error)
}
type orderRepository struct {
db *gorm.DB
auditRepo AuditRepository
}
func NewOrderRepository(db *gorm.DB, auditRepo AuditRepository) OrderRepository {
return &orderRepository{
db: db,
auditRepo: auditRepo,
}
}
func (r *orderRepository) Create(ctx context.Context, order *Order) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// Create order
if err := tx.Create(order).Error; err != nil {
return err
}
// Log audit
newValue, _ := json.Marshal(order)
return r.auditRepo.Log(ctx, AuditEntry{
TableName: "orders",
RecordID: fmt.Sprintf("%d", order.ID),
Operation: "CREATE",
NewValue: newValue,
})
})
}
func (r *orderRepository) Update(ctx context.Context, order *Order) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// Get old values
var oldOrder Order
if err := tx.First(&oldOrder, order.ID).Error; err != nil {
return err
}
// Update order
if err := tx.Save(order).Error; err != nil {
return err
}
// Log audit
oldValue, _ := json.Marshal(oldOrder)
newValue, _ := json.Marshal(order)
return r.auditRepo.Log(ctx, AuditEntry{
TableName: "orders",
RecordID: fmt.Sprintf("%d", order.ID),
Operation: "UPDATE",
OldValue: oldValue,
NewValue: newValue,
})
})
}
func (r *orderRepository) Delete(ctx context.Context, id uint) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// Get current values before delete
var order Order
if err := tx.First(&order, id).Error; err != nil {
return err
}
// Soft delete
if err := tx.Delete(&order, id).Error; err != nil {
return err
}
// Log audit
oldValue, _ := json.Marshal(order)
return r.auditRepo.Log(ctx, AuditEntry{
TableName: "orders",
RecordID: fmt.Sprintf("%d", id),
Operation: "DELETE",
OldValue: oldValue,
})
})
}Pattern 3 - State Machine with Audit Trail
Concept: Explicit state transitions with validation and audit
package statemachine
import (
"context"
"fmt"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// OrderState represents valid order states
type OrderState string
const (
StateCreated OrderState = "created"
StatePaymentPending OrderState = "payment_pending"
StatePaid OrderState = "paid"
StateProcessing OrderState = "processing"
StateShipped OrderState = "shipped"
StateDelivered OrderState = "delivered"
StateCompleted OrderState = "completed"
StateCancelled OrderState = "cancelled"
StateRefunded OrderState = "refunded"
)
// StateTransition defines valid transitions
type StateTransition struct {
FromState OrderState `gorm:"primaryKey"`
ToState OrderState `gorm:"primaryKey"`
}
// OrderStateHistory tracks state changes
type OrderStateHistory struct {
ID uint `gorm:"primaryKey"`
OrderID uint `gorm:"index;not null"`
FromState OrderState `gorm:"not null"`
ToState OrderState `gorm:"not null"`
TransitionedAt time.Time `gorm:"index;not null"`
TransitionedBy string `gorm:"index;not null"`
Reason string
SortKey int `gorm:"not null"`
IsCurrent bool `gorm:"not null;default:true"`
Metadata string `gorm:"type:jsonb"`
}
// OrderStateMachine manages order state transitions
type OrderStateMachine struct {
db *gorm.DB
}
func NewOrderStateMachine(db *gorm.DB) *OrderStateMachine {
return &OrderStateMachine{db: db}
}
// TransitionTo attempts to transition order to new state
func (sm *OrderStateMachine) TransitionTo(
ctx context.Context,
orderID uint,
toState OrderState,
user string,
reason string,
) error {
return sm.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// Lock order row
var order Order
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
First(&order, orderID).Error; err != nil {
return fmt.Errorf("order not found: %w", err)
}
currentState := OrderState(order.Status)
// Validate transition
if err := sm.validateTransition(tx, currentState, toState); err != nil {
return err
}
// Get next sort key
var maxSortKey int
tx.Model(&OrderStateHistory{}).
Where("order_id = ?", orderID).
Select("COALESCE(MAX(sort_key), 0)").
Scan(&maxSortKey)
nextSortKey := maxSortKey + 1
// Mark current state as not current
tx.Model(&OrderStateHistory{}).
Where("order_id = ? AND is_current = ?", orderID, true).
Update("is_current", false)
// Create new state history entry
history := OrderStateHistory{
OrderID: orderID,
FromState: currentState,
ToState: toState,
TransitionedAt: time.Now(),
TransitionedBy: user,
Reason: reason,
SortKey: nextSortKey,
IsCurrent: true,
}
if err := tx.Create(&history).Error; err != nil {
return fmt.Errorf("failed to create state history: %w", err)
}
// Update order status
if err := tx.Model(&order).Update("status", string(toState)).Error; err != nil {
return fmt.Errorf("failed to update order status: %w", err)
}
return nil
})
}
func (sm *OrderStateMachine) validateTransition(tx *gorm.DB, from, to OrderState) error {
var count int64
tx.Model(&StateTransition{}).
Where("from_state = ? AND to_state = ?", from, to).
Count(&count)
if count == 0 {
return fmt.Errorf("invalid state transition: %s -> %s", from, to)
}
return nil
}
// GetStateHistory returns the complete state history for an order
func (sm *OrderStateMachine) GetStateHistory(ctx context.Context, orderID uint) ([]OrderStateHistory, error) {
var history []OrderStateHistory
err := sm.db.WithContext(ctx).
Where("order_id = ?", orderID).
Order("sort_key ASC").
Find(&history).Error
return history, err
}
// GetCurrentState returns the current state of an order
func (sm *OrderStateMachine) GetCurrentState(ctx context.Context, orderID uint) (*OrderStateHistory, error) {
var history OrderStateHistory
err := sm.db.WithContext(ctx).
Where("order_id = ? AND is_current = ?", orderID, true).
First(&history).Error
return &history, err
}Pattern 4 - Middleware for API Audit Logging
Concept: HTTP middleware captures API request/response details
package middleware
import (
"bytes"
"context"
"encoding/json"
"io"
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"gorm.io/gorm"
)
// APIAuditLog represents API audit log entries
type APIAuditLog struct {
ID uint `gorm:"primaryKey"`
RequestID string `gorm:"uniqueIndex;not null"`
CorrelationID string `gorm:"index"`
SessionID string `gorm:"index"`
UserID string `gorm:"index"`
HTTPMethod string `gorm:"not null"`
Endpoint string `gorm:"not null"`
RoutePattern string `gorm:"index"`
QueryParams json.RawMessage `gorm:"type:jsonb"`
RequestBody json.RawMessage `gorm:"type:jsonb"`
RequestHeaders json.RawMessage `gorm:"type:jsonb"`
StatusCode int `gorm:"index"`
ResponseTimeMs int
ResponseBody json.RawMessage `gorm:"type:jsonb"`
ErrorMessage string
IPAddress string
UserAgent string
CreatedAt time.Time `gorm:"index"`
Metadata json.RawMessage `gorm:"type:jsonb"`
}
// APIAuditMiddleware logs all API requests and responses
func APIAuditMiddleware(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
startTime := time.Now()
// Generate request ID if not present
requestID := c.GetHeader("X-Request-ID")
if requestID == "" {
requestID = uuid.New().String()
c.Header("X-Request-ID", requestID)
}
// Store request ID in context
ctx := context.WithValue(c.Request.Context(), "request_id", requestID)
c.Request = c.Request.WithContext(ctx)
// Capture request body
var requestBody []byte
if c.Request.Body != nil {
requestBody, _ = io.ReadAll(c.Request.Body)
// Restore body for handler
c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
}
// Create custom response writer to capture response
blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
c.Writer = blw
// Process request
c.Next()
// Calculate response time
responseTime := time.Since(startTime).Milliseconds()
// Prepare audit log (async to not block response)
go func() {
auditLog := APIAuditLog{
RequestID: requestID,
CorrelationID: c.GetHeader("X-Correlation-ID"),
SessionID: c.GetString("session_id"), // From auth middleware
UserID: c.GetString("user_id"), // From auth middleware
HTTPMethod: c.Request.Method,
Endpoint: c.Request.URL.Path,
RoutePattern: c.FullPath(),
QueryParams: toJSON(c.Request.URL.Query()),
RequestBody: sanitizeRequestBody(requestBody),
RequestHeaders: toJSON(sanitizeHeaders(c.Request.Header)),
StatusCode: c.Writer.Status(),
ResponseTimeMs: int(responseTime),
ResponseBody: sanitizeResponseBody(blw.body.Bytes()),
IPAddress: c.ClientIP(),
UserAgent: c.Request.UserAgent(),
CreatedAt: startTime,
}
// Save to database
if err := db.Create(&auditLog).Error; err != nil {
// Log error but don't fail the request
log.Printf("Failed to create audit log: %v", err)
}
}()
}
}
type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w bodyLogWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
func toJSON(v interface{}) json.RawMessage {
b, _ := json.Marshal(v)
return b
}
func sanitizeRequestBody(body []byte) json.RawMessage {
if len(body) == 0 {
return nil
}
var data map[string]interface{}
if err := json.Unmarshal(body, &data); err != nil {
return nil
}
// Remove sensitive fields
sensitiveFields := []string{"password", "token", "api_key", "secret", "credit_card"}
for _, field := range sensitiveFields {
if _, exists := data[field]; exists {
data[field] = "[REDACTED]"
}
}
return toJSON(data)
}
func sanitizeResponseBody(body []byte) json.RawMessage {
// Similar to request sanitization
return sanitizeRequestBody(body)
}
func sanitizeHeaders(headers http.Header) http.Header {
sanitized := make(http.Header)
for k, v := range headers {
// Skip authorization headers
if k == "Authorization" || k == "Cookie" {
sanitized[k] = []string{"[REDACTED]"}
} else {
sanitized[k] = v
}
}
return sanitized
}The Repository's Explicit GORM Audit Write
This repository writes audit rows through an explicit function rather than a global GORM callback:
func Audit(tx *gorm.DB, actor, action, target string) error {
id, err := identifier.NewID()
if err != nil {
return err
}
return tx.Create(&models.AuditLog{
Base: models.Base{ID: id},
Actor: actor,
Action: action,
Target: target,
}).Error
}The caller passes its transaction-scoped *gorm.DB. WithinContentWrite creates the GORM transaction, acquires the editorial advisory lock and gives the callback a repository backed by that transaction. This makes the audit insert's transaction boundary visible at the call site.
GORM callbacks can centralize behavior for model lifecycle events, but they are registered at the database level and need careful rules for actor identity, bulk updates and operations that bypass model hooks. An explicit repository method makes the business operation and its audit action easy to review together.
References: GORM callbacks, GORM hooks.
Expanded from the supplied audit-log article
Write critical audit records in the same transaction
Consider this implementation:
- Update an article.
- Commit the database change.
- Start an asynchronous task to insert an audit record.
What happens if the application crashes between steps 2 and 3? The article changes, but the audit event is missing.
For a compliance-critical or business-critical write, keep the state change and its audit record within one database transaction.

The business write and its audit record share one commit or rollback decision.
The transaction should have a clear invariant:
If the business change is committed, its required audit record must also be committed.
GORM's Transaction method supports this directly: return an error to roll back or return nil to commit the operations. Every query that belongs to the transaction must use the tx handle, not the outer db handle.
This approach is not free: it adds an insert to the request path. For a small or medium-sized content API, that cost is often simpler and safer than running an asynchronous pipeline.
A minimal transaction in Go and GORM
Below is a more complete example of the transaction boundary. It uses proposed model fields to show the design, so adapt it to the actual RefactorRoom models and migrations before using it.
package editorial
import (
"context"
"encoding/json"
"fmt"
"strconv"
"time"
"gorm.io/datatypes"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type ContentEntry struct {
ID uint64 `gorm:"primaryKey"`
CurrentRevisionID *uint64
ApprovedRevisionID *uint64
}
type ContentRevision struct {
ID uint64 `gorm:"primaryKey"`
EntryID uint64
Content datatypes.JSON `gorm:"type:jsonb"`
CreatedBy string
}
type AuditLog struct {
ID uint64 `gorm:"primaryKey"`
OccurredAt time.Time
ActorID string
ActorType string
Action string
TargetType string
TargetID string
RequestID string
}
func EditArticle(
ctx context.Context,
db *gorm.DB,
entryID uint64,
actorID string,
requestID string,
payload json.RawMessage,
) error {
if !json.Valid(payload) {
return fmt.Errorf("invalid revision JSON")
}
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var entry ContentEntry
// Lock the article row to serialize competing edits.
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
First(&entry, "id = ?", entryID).Error
if err != nil {
return fmt.Errorf("load content entry: %w", err)
}
revision := ContentRevision{
EntryID: entry.ID,
Content: datatypes.JSON(payload),
CreatedBy: actorID,
}
if err := tx.Create(&revision).Error; err != nil {
return fmt.Errorf("create revision: %w", err)
}
if err := tx.Model(&entry).
Update("current_revision_id", revision.ID).Error; err != nil {
return fmt.Errorf("update revision pointer: %w", err)
}
audit := AuditLog{
OccurredAt: time.Now().UTC(),
ActorID: actorID,
ActorType: "user",
Action: "content.edit",
TargetType: "content_entry",
TargetID: strconv.FormatUint(entry.ID, 10),
RequestID: requestID,
}
if err := tx.Create(&audit).Error; err != nil {
return fmt.Errorf("create audit event: %w", err)
}
return nil // GORM commits all three writes.
})
}A few engineering details are important:
First, authentication and authorization should be checked before the edit operation. The actorID must come from trusted identity context, not an arbitrary client-provided field.
Second, this example uses SELECT ... FOR UPDATE through GORM's locking clause. Without a concurrency strategy, two editors may overwrite the current revision pointer in the wrong order. Row-level locking is one option; optimistic version checks are another.
Third, when the audit insert fails, the transaction returns an error. GORM rolls back the new revision and the pointer update together. There should not be a successful content edit without its required audit row.
Finally, this code only demonstrates the persistence boundary. A production implementation also needs request validation, permission checks, error mapping and tests. It does not include the metadata column from the optional SQL design; PostgreSQL's default value handles that field when the table has the shown default.
Further reading
Originally published on DEV Community.


