Proxy
Provides a surrogate or placeholder for another object.
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
- • 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
- • 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
How It Works
Direct Access
Client directly accesses the real object.
Basic Implementation
Caching proxy for server requests:
Real-World Example: Database Protection Proxy
Access control and audit logging for database queries: