- Learning Functional Programming in Go
- Lex Sheehan
- 125字
- 2025-02-27 05:14:36
Wrapping a client request with decorators (in main)
client := Decorate(proxyTimeoutClient,
Authorization("mysecretpassword"),
LoadBalancing(RoundRobin(0, "web01:3000", "web02:3000", "web03:3000")),
Logging(log.New(InfoHandler, "client: ", log.Ltime)),
FaultTolerance(2, time.Second),
)
Our Decorate function extends our client's functionality by iterating over each decorator in order.
Note that there are several ways to implement this wrapping functionality. We could have used recursion, line-by-line wrapping, or inline wrapping like we did earlier in this chapter:
r := NewTitlizeReader(io.LimitReader(strings.NewReader("this IS a tEsT", 12))
Using a variadic parameter in conjunction with a range construct, when we are unsure of the number of decorators we need to wrap, is probably the best choice:
func Decorate(c Client, ds ...Decorator) Client {
decorated := c
for _, decorate := range ds {
decorated = decorate(decorated)
}
return decorated
}