Skip to content

Instantly share code, notes, and snippets.

Created June 10, 2022 17:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save eekwong/2299d16882d132bba595ff96c84b07ec to your computer and use it in GitHub Desktop.
# create a rate limiter to allow the http request at max 1 token within 1 sec
# this is the best way to avoid DDOS on the server because multiple requests
# can happen in different Goroutines
rl := rate.NewLimiter(rate.Every(time.Second), 1)
# We want to set up a common base client to do all the requests
client := resty.New().
SetTLSClientConfig(&tls.Config{...}). # setup TLS
SetTimeout(30 * time.Second). # client timeout
SetBaseURL(url). # base URL for all APIs
SetHeaders(map[string]string{ # common headers
"Accept": "application/json",
"Content-Type": "application/json",
OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
# apply the rate limiter before each request
return rl.Wait(ctx)
OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
# check error after each request
if resp.IsError() {
return fmt.Errorf(
"status code: %d, response: %s",
return nil
# now we can use this base client in the following way
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment