当前位置:网站首页>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("超时了")
}
}
边栏推荐
- 电子产品“使用”和“放置”哪个寿命更长??
- Lvgl 7.11 tileview interface cycle switching
- Interface automation test postman+newman+jenkins
- 关于flickr的数据集笔记
- Trooper
- Step by step introduction of sqlsugar based development framework (13) -- package the upload component based on elementplus, which is convenient for the project
- ROS学习笔记(四)ros 无法rosdep init 或者update解决方法
- Which one of the electronic products has a longer service life??
- 第三章、数据类型和变量
- ACL 2022 | 基于最优传输的对比学习实现可解释的语义文本相似性
猜你喜欢

面试官:说说 log.Fatal 和 panic 的区别

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

OSPF---开放式最短优先路径协议

stm32F407------SPI

Wu Enda logistic regression 2

I'm also drunk. Eureka delayed registration and this pit!

Postdoctoral recruitment | West Lake University Machine Intelligence Laboratory recruitment postdoctoral / Assistant Researcher / scientific research assistant

How to fix the first row title when scrolling down in Excel table / WPS table?

Jenkins' role based authorization strategy installation configuration

Starting from business needs, open the road of efficient IDC operation and maintenance
随机推荐
交友活动记录
关于flickr的数据集笔记
03.无重复字符的最长子串
实时黄金交易平台哪个可靠安全?
第三章、数据类型和变量
Briefly describe the implementation principle of redis cluster
[Hardware Engineer] can't select components?
EDI 对接CommerceHub OrderStream
Calculation date or date formatting
我想理财,不懂,有没有保本金的理财产品?
Is it safe to open a futures account online? How to apply for a low handling fee?
吴恩达机器学习编程作业无法暂停pause问题解决
Ultimate doll 2.0 | cloud native delivery package
Jenkins' role based authorization strategy installation configuration
[knowledge atlas] practice -- Practice of question answering system based on medical knowledge atlas (Part3): rule-based problem classification
做智能硬件要考虑的产品生命周期
I2C通信——时序图
我也是醉了,Eureka 延迟注册还有这个坑!
Three dimensional function display of gray image
带你初步了解多方安全计算(MPC)