首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Go中使用context.WithTimeout()时,最佳实践是什么?

在Go中使用context.WithTimeout()时,最佳实践是什么?
EN

Stack Overflow用户
提问于 2021-01-29 06:50:53
回答 1查看 2.1K关注 0票数 0

我想使用context.WithTimeout()来处理我发出外部请求的用例,如果请求的响应太长,它将返回一个错误。

我已经实现了伪代码,如下面附加的操场链接:2解决方案:

  • 主->不期望
  • main_1 ->预期
代码语言:javascript
复制
package main

import (
    "context"
    "fmt"
    "time"
)

// I just dummy sleep in this func to produce use case this func
// need 10s to process and handle logic. 
// And this assume will be out of timeOut expect (5s)
func makeHTTPRequest(ctx context.Context) (string, error) {
    time.Sleep(time.Duration(10) * time.Second)
    return "abc", nil
}

// In main Func, I will set timeout is 5 second. 
func main() {
    var strCh = make(chan string, 1)
    ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
    defer cancel()

    fmt.Print("Begin make request\n")
    abc, err := makeHTTPRequest(ctx)
    if err != nil {
        fmt.Print("Return error\n")
        return
    }

    select {
    case <-ctx.Done():
        fmt.Printf("Return ctx error: %s\n", ctx.Err())
        return
    case strCh <- abc:
        fmt.Print("Return response\n")
        return
    }
}

func main_1() {
    var strCh = make(chan string, 1)
    var errCh = make(chan error, 1)
    ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
    defer cancel()

    go func() {
        fmt.Print("Begin make request\n")
        abc, err := makeHTTPRequest(ctx)
        if err != nil {
            fmt.Print("Return error\n")
            errCh <- err
            return
        }
        strCh <- abc

    }()
    select {
    case err := <-errCh:
        fmt.Printf("Return error: %s\n", err.Error())
        return
    case <-ctx.Done():
        fmt.Printf("Return ctx error: %s\n", ctx.Err())
        return
    case str := <-strCh:
        fmt.Printf("Return response: %s\n", str)
        return
    }
}

但是,如果使用main()函数,那么它就不能像预期的那样工作。但是,如果第二个main_1()实现使用goroutine,那么新的context.WithTimeout()可能会像预期的那样工作。

你能帮我回答这个问题吗?

特维吉

EN

回答 1

Stack Overflow用户

发布于 2021-01-29 07:08:26

如果我找对了你。有两个问题。

  1. 您想知道main()函数为什么不能工作吗?
  2. 最好的做法是什么?

Q1

main()在makeHTTPRequest阻塞,在这段时间内,上下文有超时。所以,不像预期的那样工作。

Q2

这个示例可以回答你。在main_1()中,您的代码已经是最佳实践。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65950011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档