duanben1324
2017-08-21 09:11
浏览 228
已采纳

如何在Go中检查错误是否为TLS握手超时

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?

图片转代码服务由CSDN问答提供 功能建议

我有以下代码向URL请求并检查错误。

 导入“ net / http” 
 
响应,错误:= http.Head(“ url”)
   
 
  

如何检查错误是否是由于tls握手超时引起的? 我尝试了以下操作:

  if err!= nil {
 tlsError,ok:= err。(http.tlsHandshakeTimeoutError)
如果确定{
 //处理 错误
} 
} 
   
 
 

,但是我无法访问 http.tlsHandshakeTimeoutError 类型,因为它未导出。 我还能如何检查go中的错误类型?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtds8802 2017-08-21 09:46
    已采纳

    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.

    打赏 评论

相关推荐 更多相似问题