Chapter 9: Composition patterns
June 24, 2025 ยท View on GitHub
This chapter focuses on composition patterns to demonstrate how to design packages that offer reusable and composable functionality.
Topics covered
- Effectively using composition patterns and functional programming techniques
- Leveraging field embedding and method forwarding to reuse functionality
- Understanding optional interfaces, method hiding issues, and type assertions
- Propagating request-scoped values across package APIs Using
Context - Implementing custom
slog.Handlers to log extra attributes automatically - Wrapping interfaces to modify, extend, and intercept existing behavior
- Extracting implicit behavior using anonymous interfaces
Sections
Section 1: Middleware pattern
Section 2: Logging responses
- Listing 9.3:
Durationmiddleware - Listing 9.4: Response recording
- Listing 9.5: Integrating response recording
Section 3: Interceptor pattern
- Listing 9.6: Intercepting method calls
- Listing 9.7:
StatusCodemiddleware - Listing 9.8: Integrating
StatusCode
Section 4: Optional interface pattern
Section 5: Context value propagation pattern
- Listing 9.10: Package
traceid - Listing 9.11:
traceidmiddleware - Listing 9.12:
LogHandler - Listing 9.13:
WithAttrsandWithGroup - Listing 9.14: Integrating trace IDs
Section 6: Handler chaining pattern
- Listing 9.15: A chainable custom handler type
- Listing 9.16:
Respondertype - Listing 9.17:
Errorresponse helper - Listing 9.18:
Redirectresponse helper - Listing 9.19:
Textresponse helper - Listing 9.20:
Responderhelper - Listing 9.21: Chainable handlers
Section 7: Encoding and decoding
Section 8: Wrapping and unwrapping
- Listing 9.25:
MaxBytesReaderhelper - Listing 9.26: Integrating
MaxBytesReader - Listing 9.27: Unwrapping
ResponseWriters
Section 9: Outro
- This section has no listings.