-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
5 changed files
with
78 additions
and
10 deletions.
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package geocoding | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
"time" | ||
|
||
"golang.org/x/time/rate" | ||
) | ||
|
||
// most code taken from https://gist.github.com/MelchiSalins/27c11566184116ec1629a0726e0f9af5 | ||
|
||
type httpClientWithRateLimit struct { | ||
client *http.Client | ||
Ratelimiter *rate.Limiter | ||
UserAgent string | ||
} | ||
|
||
// Do dispatches the HTTP request to the network | ||
func (c *httpClientWithRateLimit) Do(req *http.Request) (*http.Response, error) { | ||
if c.UserAgent != "" { | ||
req.Header.Set("User-Agent", c.UserAgent) | ||
} | ||
// 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 | ||
} | ||
|
||
// Returns http client with a ratelimiter | ||
func NewHttpClient(rl *rate.Limiter, userAgent string) *httpClientWithRateLimit { | ||
var tr = &http.Transport{ | ||
IdleConnTimeout: 30 * time.Second, | ||
} | ||
var client = &http.Client{Transport: tr} | ||
c := &httpClientWithRateLimit{ | ||
client: client, | ||
Ratelimiter: rl, | ||
UserAgent: userAgent, | ||
} | ||
return c | ||
} |
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