| 1 | // Copyright (c) 2021 Dillon Dixon |
| 2 | // Copyright (c) 2023 Tulir Asokan |
| 3 | // |
| 4 | // This Source Code Form is subject to the terms of the Mozilla Public |
| 5 | // License, v. 2.0. If a copy of the MPL was not distributed with this |
| 6 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 7 | |
| 8 | // Package retryafter contains a utility function for parsing the Retry-After HTTP header. |
| 9 | package retryafter |
| 10 | |
| 11 | import ( |
| 12 | "net/http" |
| 13 | "strconv" |
| 14 | "time" |
| 15 | ) |
| 16 | |
| 17 | var now = time.Now |
| 18 | |
| 19 | // Parse parses the backoff time specified in the Retry-After header if present. |
| 20 | // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After. |
| 21 | // |
| 22 | // The second parameter is the fallback duration to use if the header is not present or invalid. |
| 23 | // |
| 24 | // Example: |
| 25 | // |
| 26 | // time.Sleep(retryafter.Parse(resp.Header.Get("Retry-After"), 5*time.Second)) |
| 27 | func Parse(retryAfter string, fallback time.Duration) time.Duration { |
| 28 | if retryAfter == "" { |
| 29 | return fallback |
| 30 | } else if t, err := time.Parse(http.TimeFormat, retryAfter); err == nil { |
| 31 | return t.Sub(now()) |
| 32 | } else if seconds, err := strconv.Atoi(retryAfter); err == nil { |
| 33 | return time.Duration(seconds) * time.Second |
| 34 | } |
| 35 | |
| 36 | return fallback |
| 37 | } |
| 38 | |
| 39 | // Should returns true if the given status code indicates that the request should be retried. |
| 40 | // |
| 41 | // if retryafter.Should(resp.StatusCode, true) { |
| 42 | // time.Sleep(retryafter.Parse(resp.Header.Get("Retry-After"), 5*time.Second)) |
| 43 | // } |
| 44 | func Should(statusCode int, retryOnRateLimit bool) bool { |
| 45 | switch statusCode { |
| 46 | case http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: |
| 47 | return true |
| 48 | case http.StatusTooManyRequests: |
| 49 | return retryOnRateLimit |
| 50 | default: |
| 51 | return false |
| 52 | } |
| 53 | } |