Skip to content

Instantly share code, notes, and snippets.

@MelchiSalins
Last active September 3, 2024 17:23
Show Gist options
  • Save MelchiSalins/27c11566184116ec1629a0726e0f9af5 to your computer and use it in GitHub Desktop.
Save MelchiSalins/27c11566184116ec1629a0726e0f9af5 to your computer and use it in GitHub Desktop.
GoLang HTTP Client with Rate Limiting
package main
import (
"context"
"fmt"
"net/http"
"time"
"golang.org/x/time/rate"
)
//RLHTTPClient Rate Limited HTTP Client
type RLHTTPClient struct {
client *http.Client
Ratelimiter *rate.Limiter
}
//Do dispatches the HTTP request to the network
func (c *RLHTTPClient) Do(req *http.Request) (*http.Response, error) {
// Comment out the below 5 lines to turn off ratelimiting
ctx := context.Background()
err := c.Ratelimiter.Wait(ctx) // This is a blocking call. Honors the rate limit
if err != nil {
return nil, err
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
//NewClient return http client with a ratelimiter
func NewClient(rl *rate.Limiter) *RLHTTPClient {
c := &RLHTTPClient{
client: http.DefaultClient,
Ratelimiter: rl,
}
return c
}
func main() {
rl := rate.NewLimiter(rate.Every(10*time.Second), 50) // 50 request every 10 seconds
c := NewClient(rl)
reqURL := "https://api.btcmarkets.net/v3/markets/BTC-AUD/ticker"
req, _ := http.NewRequest("GET", reqURL, nil)
for i := 0; i < 300; i++ {
resp, err := c.Do(req)
if err != nil {
fmt.Println(err.Error())
fmt.Println(resp.StatusCode)
return
}
if resp.StatusCode == 429 {
fmt.Printf("Rate limit reached after %d requests", i)
return
}
}
}
@zdebra
Copy link

zdebra commented Jun 15, 2021

Hello, thanks for this snippet. I've created a different version where the throttling is made in the http.RoundTripper: https://gist.github.com/zdebra/10f0e284c4672e99f0cb767298f20c11

This is useful for environment where *http.Client has to be used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment