package httpclient import ( "bytes" "context" "encoding/json" "fmt" "io" "math/rand" "net/http" "net/url" "strings" "sync" "time" ) type BasicAuth struct { User string Password string } type StatusError struct { Status int URL string Body string } func (e *StatusError) Error() string { return fmt.Sprintf("HTTP %d for %s: %s", e.Status, e.URL, truncate(e.Body, 240)) } type RateLimiter struct { mu sync.Mutex interval time.Duration next time.Time } func NewRateLimiter(perSecond float64) *RateLimiter { if perSecond <= 0 { perSecond = 1 } return &RateLimiter{interval: time.Duration(float64(time.Second) / perSecond)} } func (r *RateLimiter) Wait(ctx context.Context) error { r.mu.Lock() now := time.Now() delay := time.Duration(0) if now.Before(r.next) { delay = r.next.Sub(now) } r.next = maxTime(now, r.next).Add(r.interval) r.mu.Unlock() if delay <= 0 { return nil } timer := time.NewTimer(delay) defer timer.Stop() select { case <-ctx.Done(): return ctx.Err() case <-timer.C: return nil } } type Client struct { HTTP *http.Client UA string Basic *BasicAuth Limiter *RateLimiter } func New(ua string, basic *BasicAuth, limiter *RateLimiter) *Client { return &Client{ HTTP: &http.Client{Timeout: 60 * time.Second}, UA: ua, Basic: basic, Limiter: limiter, } } func (c *Client) Get(ctx context.Context, rawURL string, params url.Values) ([]byte, http.Header, error) { if len(params) > 0 { sep := "?" if strings.Contains(rawURL, "?") { sep = "&" } rawURL += sep + params.Encode() } return c.do(ctx, http.MethodGet, rawURL, nil, nil) } func (c *Client) GetJSON(ctx context.Context, rawURL string, params url.Values, out any) error { data, _, err := c.Get(ctx, rawURL, params) if err != nil { return err } return json.Unmarshal(data, out) } func (c *Client) GetWithHeaders(ctx context.Context, rawURL string, params url.Values, headers map[string]string) ([]byte, http.Header, error) { if len(params) > 0 { sep := "?" if strings.Contains(rawURL, "?") { sep = "&" } rawURL += sep + params.Encode() } return c.do(ctx, http.MethodGet, rawURL, nil, headers) } func (c *Client) PostJSON(ctx context.Context, rawURL string, value any) ([]byte, http.Header, error) { data, err := json.Marshal(value) if err != nil { return nil, nil, err } headers := map[string]string{"Content-Type": "application/json"} return c.do(ctx, http.MethodPost, rawURL, data, headers) } func (c *Client) PostForm(ctx context.Context, rawURL string, values url.Values) ([]byte, http.Header, error) { headers := map[string]string{"Content-Type": "application/x-www-form-urlencoded"} return c.do(ctx, http.MethodPost, rawURL, []byte(values.Encode()), headers) } func (c *Client) do(ctx context.Context, method, rawURL string, body []byte, headers map[string]string) ([]byte, http.Header, error) { var lastErr error for attempt := 0; attempt <= 3; attempt++ { if c.Limiter != nil { if err := c.Limiter.Wait(ctx); err != nil { return nil, nil, err } } var bodyReader io.Reader if body != nil { bodyReader = bytes.NewReader(body) } req, err := http.NewRequestWithContext(ctx, method, rawURL, bodyReader) if err != nil { return nil, nil, err } req.Header.Set("User-Agent", c.UA) req.Header.Set("Accept", "application/json, text/plain, */*") req.Header.Set("Accept-Encoding", "identity") if c.Basic != nil { req.SetBasicAuth(c.Basic.User, c.Basic.Password) } for key, value := range headers { req.Header.Set(key, value) } resp, err := c.HTTP.Do(req) if err != nil { lastErr = err if attempt == 3 { return nil, nil, err } sleep(ctx, attempt) continue } data, readErr := io.ReadAll(resp.Body) _ = resp.Body.Close() if readErr != nil { lastErr = readErr sleep(ctx, attempt) continue } if resp.StatusCode < 400 { return data, resp.Header, nil } statusErr := &StatusError{ Status: resp.StatusCode, URL: redactURL(rawURL), Body: string(data), } if resp.StatusCode == http.StatusUnauthorized { return nil, resp.Header, statusErr } if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 { lastErr = statusErr if attempt == 3 { return nil, resp.Header, statusErr } sleep(ctx, attempt) continue } return nil, resp.Header, statusErr } return nil, nil, lastErr } func sleep(ctx context.Context, attempt int) { delay := time.Duration(1<