IsNetworkOrHostDown - if there was a network error or if the host is down. expectTimeouts indicates that *context* timeouts are expected and does not indicate a downed host. Other timeouts still returns down.
(err error, expectTimeouts bool)
| 652 | // expectTimeouts indicates that *context* timeouts are expected and does not |
| 653 | // indicate a downed host. Other timeouts still returns down. |
| 654 | func IsNetworkOrHostDown(err error, expectTimeouts bool) bool { |
| 655 | if err == nil { |
| 656 | return false |
| 657 | } |
| 658 | |
| 659 | if errors.Is(err, context.Canceled) { |
| 660 | return false |
| 661 | } |
| 662 | |
| 663 | if expectTimeouts && errors.Is(err, context.DeadlineExceeded) { |
| 664 | return false |
| 665 | } |
| 666 | |
| 667 | if errors.Is(err, context.DeadlineExceeded) { |
| 668 | return true |
| 669 | } |
| 670 | |
| 671 | // We need to figure if the error either a timeout |
| 672 | // or a non-temporary error. |
| 673 | urlErr := &url.Error{} |
| 674 | if errors.As(err, &urlErr) { |
| 675 | switch urlErr.Err.(type) { |
| 676 | case *net.DNSError, *net.OpError, net.UnknownNetworkError, *tls.CertificateVerificationError: |
| 677 | return true |
| 678 | } |
| 679 | } |
| 680 | var e net.Error |
| 681 | if errors.As(err, &e) { |
| 682 | if e.Timeout() { |
| 683 | return true |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | // Fallback to other mechanisms. |
| 688 | switch { |
| 689 | case strings.Contains(err.Error(), "Connection closed by foreign host"): |
| 690 | return true |
| 691 | case strings.Contains(err.Error(), "TLS handshake timeout"): |
| 692 | // If error is - tlsHandshakeTimeoutError. |
| 693 | return true |
| 694 | case strings.Contains(err.Error(), "i/o timeout"): |
| 695 | // If error is - tcp timeoutError. |
| 696 | return true |
| 697 | case strings.Contains(err.Error(), "connection timed out"): |
| 698 | // If err is a net.Dial timeout. |
| 699 | return true |
| 700 | case strings.Contains(err.Error(), "connection refused"): |
| 701 | // If err is connection refused |
| 702 | return true |
| 703 | case strings.Contains(err.Error(), "server gave HTTP response to HTTPS client"): |
| 704 | // If err is TLS client is used with HTTP server |
| 705 | return true |
| 706 | case strings.Contains(err.Error(), "Client sent an HTTP request to an HTTPS server"): |
| 707 | // If err is plain-text Client is used with a HTTPS server |
| 708 | return true |
| 709 | case strings.Contains(strings.ToLower(err.Error()), "503 service unavailable"): |
| 710 | // Denial errors |
| 711 | return true |
no test coverage detected