A consumer-driven interface is declared by the package that uses it, around the operations that consumer actually needs. In Go, this lets an HTTP handler depend on behavior rather than a concrete storage implementation. section 10.0 section 10.4.1
This approach keeps interfaces practical:
- Declare only essential methods, avoiding speculative or bloated contracts. section 10.4.1
- Accept any provider whose methods satisfy the consumer’s interface; Go’s implicit interfaces require no explicit implementation declaration. section 10.4.1
- Limit cascading changes when a provider later adds methods to its concrete type. section 10.4.1
- Keep contracts easier to understand, test, satisfy, and compose. section 10.4.1
Handlers declare the interfaces they consume
The rest package can define one-method interfaces matching its current needs: Shortener exposes Shorten, and Resolver exposes Resolve. Its handlers accept these interfaces instead of concrete services. Both link.Shortener and sqlite.Shortener can therefore be passed to the handlers, while future storage implementations such as a cache or cloud database require no handler changes. section 10.4.2
Figure 10.6 The consumer (rest) owns the interface rather than the provider (sqlite).
Diagram showing the consumer package owning the interface rather than the provider package. section 10.4.1
Declare an interface when a consumer needs one, rather than defining every possible abstraction up front. The result is a smaller contract, clearer separation of concerns, and looser coupling between handlers and implementations. section 10.4.2 section 10.4.1
