2017-08-21 28 views
0

我有以下代碼向URL發出請求並檢查錯誤。如何檢查錯誤是否在Go中發生握手超時

import "net/http" 

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

如何檢查錯誤是否由於握手超時?我試過以下內容:

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

但是我無法訪問http.tlsHandshakeTimeoutError類型,因爲它是未導出的。我還有什麼可以檢查錯誤類型嗎?

回答

2

tlsHandshakeTimeoutError - 不出口,只有一個 可能性來檢查這個錯誤是:

import "net/url" 

// .... 

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

這裏是公開售票與討論一下:

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

由方式http錯誤(和tlsHandshakeTimeoutError也)也提供:

type WithTimeout interface { 
    Timeout() bool 
} 

你可以用它來檢查你是否喜歡字符串比較。 Here是http2包中的isTemporary實現的示例。

+0

這是Go作者非常愚蠢的設計選擇。鑑於其他類似的怪癖,我並不感到驚訝。 – Mikhail

+1

其實這並不完全正確,因爲我需要在字符串中包含方法和url進行比較,所以答案應該是:'if err.Error()==「Head」+「net/http:TLS handshake tmieout 「{//處理錯誤}」' – Mikhail

+1

你是對的這個錯誤是由Do方法包裝的我已經更新了我的答案,但無論如何,這個想法是相同的 - 只是字符串檢查 – Oleg