Skip to content

Instantly share code, notes, and snippets.

@eekwong
Created Jun 10, 2022
Embed
What would you like to do?
# 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",
resp.StatusCode(),
resp.String(),
)
}
return nil
})
# now we can use this base client in the following way
client.R().
SetContext(ctx).
SetBody(...).
SetResult(...).
Post(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment