fetchWithRateLimitHandling fetches the document from the given URL and handles 403 rate limiting or connection errors.
(url string)
| 263 | |
| 264 | // fetchWithRateLimitHandling fetches the document from the given URL and handles 403 rate limiting or connection errors. |
| 265 | func 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 | |
| 317 | func downloadAndSaveAsWARC(url string) { |
| 318 | // Get the current date |
no outgoing calls
no test coverage detected