9 Composition patterns
This chapter covers
- Composition patterns and functional programming techniques.
- Field embedding and method forwarding to provide extra functionality.
- Optional interfaces, method hiding issues, and type assertions.
- Using Context to propagate values across packages APIs.
- Implementing a custom slog.Handler to log extra log attributes.
- Interface wrapping techniques to change existing behavior.
- Effectively using anonymous interfaces for extracting behavior.
Lastly, we implemented Bite's link service. We discussed structuring multiple packages and developed a REST API over HTTP. In this chapter, we'll extend our project with additional packages focusing on middleware, logging, Context value propagation, and composition.
We'll discuss functional compositional patterns to demonstrate how to design packages that offer reusable and composable functionality, showcasing HTTP middleware. We'll then dive into propagating trace IDs and explain how to write custom log handlers. Lastly, we'll discover a handler chaining pattern for writing robust and convenient HTTP handlers.
"If C++ and Java are about type hierarchies and the taxonomy of types, Go is about composition."
— Rob Pike, from his "Less is exponentially more" article