Structural

Proxy

Provides a surrogate or placeholder for another object.

Lazy loadingAccess controlRemote objects

Understanding Proxy

The Proxy pattern provides a surrogate or placeholder object that controls access to another object — the real subject. The proxy implements the same interface as the real object, so client code can't tell the difference. In Go, proxies are commonly used for caching (return cached results instead of hitting the real service), access control (check permissions before delegating), lazy loading (defer expensive initialization until first use), and logging (audit all operations transparently). Since Go interfaces are satisfied implicitly, any struct implementing the right methods can serve as a proxy.

Key Concepts

  • Same interface — proxy implements the exact same interface as the real subject, making it a transparent substitute
  • Access control — protection proxies check permissions or credentials before forwarding to the real object
  • Caching proxy — stores results from expensive operations and returns cached values on subsequent calls
  • Lazy initialization — virtual proxies defer creating the real object until it is actually needed

When to Use

✅ Use when
  • • You need access control, caching, or logging without modifying the real object
  • • Object initialization is expensive and should be deferred until first use
  • • You need to add a layer of indirection for remote objects (RPC, network)
  • • You want to count or audit references to an object
⚠️ Avoid when
  • • The overhead of the proxy layer isn't justified by the benefit
  • • Direct access is simpler and the proxy adds unnecessary complexity
  • • Go middleware or functional composition is a better fit for the use case

Structure

Client
↓ calls interface
Proxy (check/cache/log)
↓ delegates to
RealSubject

How It Works

Client
Proxy
Cache/Auth/Log
Real Server
Direct access (no control)
1

Direct Access

Client directly accesses the real object.

1 / 4

Basic Implementation

Caching proxy for server requests:

main.go
Loading editor...

Real-World Example: Database Protection Proxy

Access control and audit logging for database queries:

main.go
Loading editor...