go语言context控制函数执行超时返回

用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("超时了")
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值