Created
June 10, 2022 17:43
-
-
Save eekwong/2299d16882d132bba595ff96c84b07ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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