使用Golang 1.20.1.
在Golang的net/http和上下文包中,我无法设置超过30秒的超时.设置较短的超时时间很好,例如
代码:
log.Infof("Elasticsearch URL is %v", elasticsearchURL)
client := &http.Client{Timeout: time.Duration(time.Second * 60)}
req, err := http.NewRequest("GET", listBackupsURL, nil)
if err != nil {
internalError(w, fmt.Sprintf("error creating request: %v", err))
return
}
req.SetBasicAuth(username, password)
resp, err := client.Do(req)
if err != nil {
// handle error
internalError(w, fmt.Sprintf("error accessing elasticsearch: %v", err))
return
}
日志(log):
I0503 23:01:55.973821 1 somecode.go:85] URL is http://elasticsearch.example.ingest:9200
E0503 23:02:25.976345 1 caller_handler.go:63] 500 Internal Server Error: error accessing elasticsearch: Get "http://elasticsearch.example.ingest:9200/_cat/snapshots/object-store-repo?v&s=id": dial tcp 1.2.3.4:9200: i/o timeout
超时时间是30秒,而不是60秒.
如果我使用http.NewRequestWithContext(...)
并使用上下文设置相同的超时,我会得到相同的行为:
代码:
log.Infof("Elasticsearch URL is %v", elasticsearchURL)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Second * 60))
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", listBackupsURL, nil)
if err != nil {
internalError(w, fmt.Sprintf("error creating request: %v", err))
return
}
req.SetBasicAuth(username, password)
resp, err := client.Do(req)
if err != nil {
// handle error
internalError(w, fmt.Sprintf("error accessing elasticsearch: %v", err))
return
}
日志(log):
I0503 23:31:10.941169 1 somecode.go:85] Elasticsearch URL is http://elasticsearch.example.ingest:9200
E0503 23:31:40.941642 1 caller_handler.go:63] 500 Internal Server Error: error accessing elasticsearch: Get "http://elasticsearch.example.ingest:9200/_cat/snapshots/object-store-repo?v&s=id": dial tcp 1.2.3.4:9200: i/o timeout
但是,如果我将超时更改为3秒(在任何一种方法中都是time.Duration(time.Second * 3))
秒),它将按预期工作:
I0503 23:44:17.622121 1 somecode.go:85] Elasticsearch URL is http://elasticsearch.example.ingest:9200
E0503 23:44:20.624795 1 caller_handler.go:63] 500 Internal Server Error: error accessing elasticsearch: Get "http://elasticsearch.example.ingest:9200/_cat/snapshots/object-store-repo?v&s=id": context deadline exceeded (Client.Timeout exceeded while awaiting headers)