|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net/http" |
| 6 | +) |
| 7 | + |
| 8 | +// HTTP is a HTTP client. |
| 9 | +type HTTP struct { |
| 10 | + client *http.Client |
| 11 | + limiter Limiter |
| 12 | +} |
| 13 | + |
| 14 | +// Options are client options |
| 15 | +type Options struct { |
| 16 | + HTTPClient *http.Client |
| 17 | + Limiter Limiter |
| 18 | +} |
| 19 | + |
| 20 | +// Option is functional graph option. |
| 21 | +type Option func(*Options) |
| 22 | + |
| 23 | +// Limiter is used to apply rate limits. |
| 24 | +// NOTE: you can use off the shelf limiter from |
| 25 | +// https://pkg.go.dev/golang.org/x/time/rate#Limiter |
| 26 | +type Limiter interface { |
| 27 | + // Wait must block until limiter |
| 28 | + // permits another request to proceed. |
| 29 | + Wait(context.Context) error |
| 30 | +} |
| 31 | + |
| 32 | +// NewHTTP creates a new HTTP client and returns it. |
| 33 | +func NewHTTP(opts ...Option) *HTTP { |
| 34 | + options := Options{ |
| 35 | + HTTPClient: &http.Client{}, |
| 36 | + } |
| 37 | + for _, apply := range opts { |
| 38 | + apply(&options) |
| 39 | + } |
| 40 | + |
| 41 | + return &HTTP{ |
| 42 | + client: options.HTTPClient, |
| 43 | + limiter: options.Limiter, |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// Do dispatches the HTTP request to the network |
| 48 | +func (h *HTTP) Do(req *http.Request) (*http.Response, error) { |
| 49 | + if h.limiter != nil { |
| 50 | + err := h.limiter.Wait(req.Context()) // This is a blocking call. Honors the rate limit |
| 51 | + if err != nil { |
| 52 | + return nil, err |
| 53 | + } |
| 54 | + } |
| 55 | + resp, err := h.client.Do(req) |
| 56 | + if err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + return resp, nil |
| 60 | +} |
| 61 | + |
| 62 | +// WithHTTPClient sets the HTTP client. |
| 63 | +func WithHTTPClient(c *http.Client) Option { |
| 64 | + return func(o *Options) { |
| 65 | + o.HTTPClient = c |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +// WithLimiter sets the http rate limiter. |
| 70 | +func WithLimiter(l Limiter) Option { |
| 71 | + return func(o *Options) { |
| 72 | + o.Limiter = l |
| 73 | + } |
| 74 | +} |
0 commit comments