当前位置:网站首页>go语言context控制函数执行超时返回
go语言context控制函数执行超时返回
2022-07-25 17:36:00 【kankan231】
用go语言实现请求url的内容,当超过指定时间自动返回
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)
}
//获取url的内容,并设定超时事件
func getUrlContent(url string, timeout time.Duration) (string, error) {
type Resp struct {
content string
err error
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)//超时控制context
defer cancel()//函数返回时调用cancel,避免内存泄露
ch := make(chan Resp,1)//子协程结束时将返回值放入该通道,通知当前协程子协程已结束
go func() {//开启子协程获取url内容
res, err := http.Get(url)
if err != nil {
ch <- Resp{"", err}
return
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)//读取内容
if err != nil {
ch <- Resp{"", err}
return
}
ch <- Resp{string(body), nil}
}()
//当前协程等待,监听通道可读事件
select {
case resp := <-ch://子协程结束事件
return resp.content, resp.err
case <-ctx.Done()://超时事件
return "", errors.New("超时了")
}
}
边栏推荐
- ACL 2022 | comparative learning based on optimal transmission to achieve interpretable semantic text similarity
- 交叉验证(cv)学习笔记
- 【无标题】
- Using rank to discuss the solution of linear equations / the positional relationship of three planes
- Beyond convnext, replknet | look 51 × 51 convolution kernel how to break ten thousand volumes!
- 【Cadence Allegro PCB设计】永久修改快捷键(自定义)~亲测有效~
- How to rectify the unqualified EMC of electronic products?
- Methods of de duplication and connection query in MySQL database
- 服务器端架构设计期末复习知识点总结
- WPF implements user avatar selector
猜你喜欢

Thesis reading_ Multi task learning_ MMoE

Cet

WPF 实现用户头像选择器

四六级

Add batch delete

Tkinter module advanced operations (I) -- transparent buttons, transparent text boxes, custom buttons and custom text boxes
![[knowledge atlas] practice -- Practice of question answering system based on medical knowledge atlas (Part4): problem analysis and retrieval sentence generation combined with problem classification](/img/22/01297d28e5bfb105fc65ee29248a7c.png)
[knowledge atlas] practice -- Practice of question answering system based on medical knowledge atlas (Part4): problem analysis and retrieval sentence generation combined with problem classification

对灰度图像的三维函数显示

哈夫曼树的构建

什么是 IP SSL 证书,如何申请?
随机推荐
POWERBOARD coco! Dino: let target detection embrace transformer
【硬件工程师】DC-DC隔离式开关电源模块为什么会用到变压器?
Random talk on generation diffusion model: DDPM = Bayesian + denoising
WPF implements user avatar selector
The gas is exhausted! After 23 years of operation, the former "largest e-commerce website in China" has become yellow...
EDI 对接CommerceHub OrderStream
交友活动记录
WPF implements user avatar selector
Summary of 80 domestic database operation documents (including tidb, Damon, opengauss, etc.)
大型仿人机器人的技术难点和应用情况
我也是醉了,Eureka 延迟注册还有这个坑!
接口自动化测试Postman+Newman+Jenkins
window10系统下nvm的安装步骤以及使用方法
【硬件工程师】元器件选型都不会?
Tkinter module advanced operations (I) -- transparent buttons, transparent text boxes, custom buttons and custom text boxes
Three dimensional function display of gray image
PostgreSQL passwords are case sensitive. Is there parameter control?
论文阅读_多任务学习_MMoE
【Cadence Allegro PCB设计】error: Possible pin type conflict GND/VCC Power Connected to Output
Redis源码与设计剖析 -- 16.AOF持久化机制