之前遇到了很多 timeout,但是仔細看錯誤提示好像不完全一樣,於是就做了個簡單的試驗:
Client 上看到的錯誤
找不到服務器(no such host
)的幾種情況:
# 域名不存在,瞄了下代碼,應該是 dns 包返回的 Get http://a.b/abc: dial tcp: lookup a.b: no such host # ip 不合法不會直接檢查,也會返回同樣錯誤 Get http://127.0.0.1888:8080/abc: dial tcp: lookup 127.0.0.1888: no such host # 端口瞎填會直接報錯,都不會發請求 Get http://127.0.0.1:65536/abc: dial tcp: address 65536: invalid port
拒絕連接,對方端口未監聽、進程掛掉等等
Get http://127.0.0.1:8080/abc: dial tcp 127.0.0.1:8080: connect: connection refused
建立連接超時
Get http://127.0.0:8080/abc: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
等待返回 header, 一般是接口還在處理邏輯,沒有返回任何數據;或者對方只是個普通的 tcp 服務,但不是 http
Get http://127.0.0.1:8080/abc: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
客戶端讀取超時:已建立好連接,已經開始返回數據,但是body 太大太慢:
wait_test.go:48: net/http: request canceled (Client.Timeout exceeded while reading body)
Server 上看到的錯誤
客戶端主動斷開連接,服務器端在調用 Write(p []byte) (n int, err error)
時會返回:
wait_test.go:21: write tcp 127.0.0.1:8080->127.0.0.1:49290: write: broken pipe
客戶端主動斷開連接,通常會直接使用 ctx.Done()
檢測到,這個時候 ctx.Err()
裡會拿到這個信息:
context canceled
參考連結
https://romatic.net/post/go_net_errors/
https://colobu.com/2016/07/01/the-complete-guide-to-golang-net-http-timeouts/