go 设置http请求超时时间
10.11.12.13不真实存在,ping会超时。
使用 http.Client 设置全局超时
package main
import (
"net/http"
"time"
)
func main() {
client := &http.Client{
Timeout: 5 * time.Second, // 设置总超时时间(包括连接、请求和响应)
}
resp, err := client.Get("https://10.11.12.13:443")
if err != nil {
return
}
defer resp.Body.Close()
}

使用context设置单个请求超时
package main
import (
"context"
"net/http"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", "https://10.11.12.13:443", nil)
if err != nil {
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
}

go 设置http请求超时时间
package main
import (
"net"
"net/http"
"time"
)
func main() {
client := &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 1 * time.Second, // 连接超时
}).DialContext,
TLSHandshakeTimeout: 700 * time.Millisecond, // TLS握手超时
ResponseHeaderTimeout: 300 * time.Millisecond, // 响应头超时
ExpectContinueTimeout: 500 * time.Millisecond, // 100-continue等待超时
},
Timeout: 5 * time.Second, // 总超时
}
resp, err := client.Get("https://10.11.12.13:443")
if err != nil {
return
}
defer resp.Body.Close()
}

使用http.Server设置细粒度超时时间
package main
import (
"net/http"
"time"
)
func main() {
srv := &http.Server{
Addr: ":443",
ReadTimeout: 1 * time.Second, // 读取请求头的超时
WriteTimeout: 3 * time.Second, // 写入响应的超时
IdleTimeout: 5 * time.Second, // keep-alive 连接的空闲超时
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
srv.ListenAndServe()
}
浙公网安备 33010602011771号