使用Context控制请求超时可避免资源浪费和系统阻塞。通过context.WithTimeout创建带超时的Context,传递给HTTP请求,若超时则自动取消,释放资源并提升系统稳定性。

使用context控制请求超时,核心在于利用
context.WithTimeout
context.WithDeadline
package main
import (
"context"
"fmt"
"net/http"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", "https://www.example.com", nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer resp.Body.Close()
fmt.Println("Response Status:", resp.Status)
}为什么需要使用Context控制请求超时?
资源浪费!如果一个请求因为网络问题或者服务器压力过大而长时间得不到响应,那么程序会一直等待,消耗系统资源。使用超时控制可以避免这种情况,及时释放资源。另外,超时机制可以提高系统的稳定性和用户体验,避免因为个别请求的阻塞而影响整体性能。
如何在不同的Golang HTTP客户端中使用Context超时控制?
立即学习“go语言免费学习笔记(深入)”;
除了标准库的
net/http
net/http
http.NewRequestWithContext
client.Do
go-resty
go-resty
R().SetContext(ctx).Get(url)
fasthttp
fasthttp
Done()
// go-resty 示例
package main
import (
"context"
"fmt"
"time"
"github.com/go-resty/resty/v2"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
client := resty.New()
resp, err := client.R().
SetContext(ctx).
Get("https://www.example.com")
if err != nil {
fmt.Println("Error making request:", err)
return
}
fmt.Println("Response Status:", resp.Status())
}Context超时控制的常见错误和陷阱有哪些?
cancel()
context.WithTimeout
context.WithDeadline
cancel()
client.Do
context.DeadlineExceeded
// 示例:正确处理超时错误
package main
import (
"context"
"fmt"
"net/http"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", "https://www.example.com", nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
if err == context.DeadlineExceeded {
fmt.Println("Request timed out!")
} else {
fmt.Println("Error making request:", err)
}
return
}
defer resp.Body.Close()
fmt.Println("Response Status:", resp.Status)
}以上就是Golang使用context控制请求超时示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号