当前位置:网站首页>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("超时了")
}
}
边栏推荐
- With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development
- Chapter VI succession
- ROS学习笔记(四)ros 无法rosdep init 或者update解决方法
- Chapter III data types and variables
- window10系统下nvm的安装步骤以及使用方法
- 【硬件工程师】关于信号电平驱动能力
- 走马卒
- Redis源码与设计剖析 -- 15.RDB持久化机制
- [PHP pseudo protocol] source code reading, file reading and writing, and arbitrary PHP command execution
- 博后招募 | 西湖大学机器智能实验室招聘博士后/助理研究员/科研助理
猜你喜欢

Technical difficulties and applications of large humanoid robots
![[knowledge atlas] practice -- Practice of question and answer system based on medical knowledge atlas (Part5 end): information retrieval and result assembly](/img/47/e70f6b86f4dded3218370da7394a07.png)
[knowledge atlas] practice -- Practice of question and answer system based on medical knowledge atlas (Part5 end): information retrieval and result assembly

我也是醉了,Eureka 延迟注册还有这个坑!

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

自动化测试 PO设计模型

大型仿人机器人的技术难点和应用情况

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

Thesis reading_ Multi task learning_ MMoE

HCIP第一天实验

什么是 IP SSL 证书,如何申请?
随机推荐
Briefly describe the implementation principle of redis cluster
多项式相加
8 年产品经验,我总结了这些持续高效研发实践经验 · 研发篇
Chapter III data types and variables
WPF implements user avatar selector
stm32F407------SPI
Three dimensional function display of gray image
约瑟夫环问题
An article about ultrasonic humidifier
Postdoctoral recruitment | West Lake University Machine Intelligence Laboratory recruitment postdoctoral / Assistant Researcher / scientific research assistant
Redis源码与设计剖析 -- 15.RDB持久化机制
对灰度图像的三维函数显示
Add batch delete
[knowledge atlas] practice -- Practice of question answering system based on medical knowledge atlas (Part4): problem analysis and retrieval sentence generation combined with problem classification
大型仿人机器人的技术难点和应用情况
ACL 2022 | comparative learning based on optimal transmission to achieve interpretable semantic text similarity
双向链表的基本操作
咨询下flink sql-client怎么处理DDL后,fink sql里面映射表加字段以及JOb?
I2C通信——时序图
Does PgSQL have a useful graphical management tool?