The proxy pattern in Go
This is a continuation of the common design patterns I found in my old code series, which I started in a previous post.
The proxy pattern is a design pattern in which a class (proxy) acts as an interface to something else. The proxy could be an interface to anything: a network connection, another class, a file, etc.
A proxy can be useful in a variety of situations:
- A frontend for load balancing
- Hide private infrastructure
- Caching layer
- etc
A good example of a proxy that can be used as a load balancer (and other purposes) is nginx or net/http/httputil (the ReverseProxy
).
To illustrate how to use this pattern in Go, let’s implement a simple caching layer for files to speed up multiple reads for the same files:
|
|
And if you’d run a simple benchmark:
|
|
|
|
You can see how the proxy could improve your app performance in a similar situation.
And that’s it. I hope this example has shed some light on how the proxy pattern works and can be used to improve your code performance.
For more design pattern examples, please checkout rolandjitsu/go-design-patterns.
If you find this post helpful, please consider sponsoring.
Sponsor