- Learning Functional Programming in Go
- Lex Sheehan
- 140字
- 2021-07-02 23:13:54
The decorator/decorator.go file
Let's look at our decorator.go implementation. It's in the 02_decorator directory, and the package name is decorator:
package decorator
import (
"log"
"net/http"
"sync/atomic"
"time"
)
type Client interface {
Do(*http.Request) (*http.Response, error)
}
// ClientFunc is a function type that implements the client interface.
type ClientFunc func(*http.Request) (*http.Response, error)
func (f ClientFunc) Do(r *http.Request) (*http.Response, error) {
return f(r)
}
The ClientFunc function is a function type that implements the Client interface.
We also define two additional methods that act as the getter and setter for the ratelimitDuration value:
var ratelimitDuration time.Duration
func (f ClientFunc) SetRatelimit(duration time.Duration) (error) {
ratelimitDuration = duration
return nil
}
func (f ClientFunc) GetRatelimit() (time.Duration, error) {
return ratelimitDuration, nil
}
Next, we define the Decorator function type to wrap our Client with additional behavior:
type Decorator func(Client) Client