当前位置:网站首页>Go language context control function execution timeout return
Go language context control function execution timeout return
2022-07-25 17:39:00 【kankan231】
use go Language implementation request url The content of , When it exceeds the specified time, it will automatically return
package main
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"time"
)
func main() {
content, err := getUrlContent("https://github.com/", 500*time.Millisecond)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(content)
}
// obtain url The content of , And set the timeout event
func getUrlContent(url string, timeout time.Duration) (string, error) {
type Resp struct {
content string
err error
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)// Timeout control context
defer cancel()// When the function returns, call cancel, Avoid memory leaks
ch := make(chan Resp,1)// At the end of the subprocess, put the return value into the channel , Inform the current process that the sub process has ended
go func() {// Open the subprocess to get url Content
res, err := http.Get(url)
if err != nil {
ch <- Resp{"", err}
return
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)// Read the content
if err != nil {
ch <- Resp{"", err}
return
}
ch <- Resp{string(body), nil}
}()
// Current coordination process waiting , Listen for channel readable events
select {
case resp := <-ch:// Sub process end event
return resp.content, resp.err
case <-ctx.Done():// Timeout Events
return "", errors.New(" It's overtime ")
}
}
边栏推荐
- WPF 实现用户头像选择器
- WPF implements user avatar selector
- 做智能硬件要考虑的产品生命周期
- Using rank to discuss the solution of linear equations / the positional relationship of three planes
- Chapter VI succession
- Summary of knowledge points for final review of server-side architecture design
- 【硬件工程师】DC-DC隔离式开关电源模块为什么会用到变压器?
- Summary of 80 domestic database operation documents (including tidb, Damon, opengauss, etc.)
- Notes on Flickr's dataset
- Methods of de duplication and connection query in MySQL database
猜你喜欢

With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development

Idea essential plug-ins

计算日期或日期格式化

Redis源码与设计剖析 -- 16.AOF持久化机制

stm32F407------SPI

Add batch delete

一篇文章了解超声波加湿器

ACL 2022 | 基于最优传输的对比学习实现可解释的语义文本相似性

Redis源码与设计剖析 -- 17.Redis事件处理

【解决方案】Microsoft Edge 浏览器 出现“无法访问该页面”问题
随机推荐
博后招募 | 西湖大学机器智能实验室招聘博士后/助理研究员/科研助理
吴恩达机器学习编程作业无法暂停pause问题解决
go channel简单笔记
更新|3DCAT实时云渲染 v2.1.2版本全新发布
服务器端架构设计期末复习知识点总结
Redis源码与设计剖析 -- 17.Redis事件处理
世界各地的标志性建筑物
枚举类和魔术值
【解决方案】Microsoft Edge 浏览器 出现“无法访问该页面”问题
Add batch delete
WPF 实现用户头像选择器
Google Earth engine - download the globalmlbuildingfootprints vector collection of global buildings
什么是 IP SSL 证书,如何申请?
After consulting about how to deal with DDL in Flink SQL client, how to add fields and jobs to the mapping table in Fink SQL?
Food safety | eight questions and eight answers take you to know crayfish again! This is the right way to eat!
Redis源码与设计剖析 -- 18.Redis网络连接库分析
[vscode] support argparser/ accept command line parameters
ROS学习笔记(四)ros 无法rosdep init 或者update解决方法
What financial products can you buy to make money with only 1000 yuan?
接口自动化测试Postman+Newman+Jenkins