9 Composition patterns

 

This chapter covers

  • Effectively using composition patterns and functional programming techniques
  • Using 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

In chapter 8, we implemented a link service, discussed structuring packages, and developed a REST API over HTTP. In this chapter, we’ll extend our project, focusing on composition.

In his “Less is exponentially more” article (https://mng.bz/JwN0), Rob Pike says, “If C++ and Java are about type hierarchies and the taxonomy of types, Go is about composition.” We may be used to inheritance-based designs, large frameworks, or large manager types when we come from other languages. By contrast, Go’s philosophy is similar to UNIX’s: do one thing well. Our packages provide simple, reusable pieces that allow users to compose them together on top of what we provide.

9.1 Middleware pattern

9.1.1 What is HTTP middleware?

9.1.2 Example

9.1.3 Practice

9.1.4 Learning more about the slog package and the any interface

9.1.5 Integration

9.2 Logging responses

9.2.1 Measuring durations

9.2.2 Response recording

9.2.3 Integration

9.3 Interceptor pattern

9.3.1 Field embedding

9.3.2 Capturing and saving

9.3.3 Integration

9.3.4 Demonstration

9.4 Optional interface pattern

9.4.1 Type asserting for optional functionality