MCPcopy Create free account
hub / github.com/SecurityRunners/awsdocs / fetchWithRateLimitHandling

Function fetchWithRateLimitHandling

main.go:265–315  ·  view source on GitHub ↗

fetchWithRateLimitHandling fetches the document from the given URL and handles 403 rate limiting or connection errors.

(url string)

Source from the content-addressed store, hash-verified

263
264// fetchWithRateLimitHandling fetches the document from the given URL and handles 403 rate limiting or connection errors.
265func fetchWithRateLimitHandling(url string) (*http.Response, error) {
266 maxRetries := 5
267 for retries := 0; retries < maxRetries; retries++ {
268 // Randomly select a user agent from the list
269 userAgent := userAgents[rand.Intn(len(userAgents))]
270
271 // Create a new HTTP request
272 req, err := http.NewRequest("GET", url, nil)
273 if err != nil {
274 return nil, err
275 }
276
277 // Set the user agent header
278 req.Header.Set("User-Agent", userAgent)
279
280 // Send the request
281 client := &http.Client{}
282 resp, err := client.Do(req)
283 if err != nil {
284 // Check if it's a temporary network error
285 if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
286 log.Printf("Temporary error fetching URL: %v, retrying in %s", err, sleepDuration)
287 time.Sleep(sleepDuration)
288 continue
289 } else {
290 // Non-recoverable error, log and exit
291 log.Printf("Error fetching URL: %v", err)
292 return nil, err
293 }
294 }
295
296 // If successful response, return it
297 if resp.StatusCode == http.StatusOK {
298 return resp, nil
299 }
300
301 // Handle rate limiting (403 Forbidden)
302 if resp.StatusCode == http.StatusForbidden {
303 log.Printf("Received 403 Forbidden (rate limit), pausing for %s before retrying...", sleepDuration)
304 time.Sleep(sleepDuration)
305 resp.Body.Close()
306 continue
307 }
308
309 // Handle other unexpected status codes
310 log.Printf("Unexpected status code: %d for URL %s", resp.StatusCode, url)
311 resp.Body.Close()
312 return nil, fmt.Errorf("unexpected status code: %d for URL %s", resp.StatusCode, url)
313 }
314 return nil, fmt.Errorf("max retries exceeded for URL %s", url)
315}
316
317func downloadAndSaveAsWARC(url string) {
318 // Get the current date

Callers 3

fetchAndParseSitemapFunction · 0.85
downloadAndSaveAsWARCFunction · 0.85
downloadAndSaveAsHTMLFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected