简体   繁体   中英

How to check if error is tls handshake timeout in Go

I have the following code making a request to URL and checking for errors.

import "net/http"

response, err := http.Head("url")

How do check if the error is due to tls handshake timeout? I tried the following:

if err != nil {
    tlsError, ok := err.(http.tlsHandshakeTimeoutError)
    if ok {
        // handle the error
    }
}

But I cannot access the http.tlsHandshakeTimeoutError type because it is unexported. How else can I check for the error type in go?

Yes tlsHandshakeTimeoutError - is not exported and the only one possibility to check on this error is:

import "net/url"

// ....

if urlError,ok :=  err.(*url.Error)  ; ok {
    if urlError.Error() == "net/http: TLS handshake timeout" {
        // handle the error
    }
}

Here is open ticket with discussion about it:

https://github.com/golang/go/issues/15935

By the way http errors (and tlsHandshakeTimeoutError also) provide also:

type WithTimeout interface {
   Timeout() bool
}

You can use it for you check if you don't like string comparsion. Here is example of isTemporary implementation from http2 package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM