第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

與上下文一起使用時的最佳做法是什么?WithTimeout() in Go?

與上下文一起使用時的最佳做法是什么?WithTimeout() in Go?

Go
紫衣仙女 2022-08-01 18:59:16
我想用來處理我發(fā)出外部請求的用例,如果請求的響應太長,它將返回錯誤。context.WithTimeout()我已經(jīng)實現(xiàn)了偽代碼,如下面附帶的 playground 鏈接:2 解決方案:主->未預料到預計main_1 ->package mainimport (    "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    }}但是,如果使用該函數(shù),則它無法按預期工作。但是,如果使用goroutine進行第二種實現(xiàn),那么也許新的實現(xiàn)可以按預期工作。main()main_1()context.WithTimeout()你能幫我回答這個問題嗎?https://play.golang.org/p/kZdlm_Tvljy
查看完整描述

2 回答

?
HUX布斯

TA貢獻1876條經(jīng)驗 獲得超6個贊

最好在函數(shù)中處理上下文,這樣就可以將其用作 中的同步函數(shù)。makeHTTPRequest()main()


https://play.golang.org/p/Bhl4qprIBgH


func makeHTTPRequest(ctx context.Context) (string, error) {

    ch := make(chan string)


    go func() {

        time.Sleep(10 * time.Second)

        select {

        case ch <- "abc":

        default:

            // When context deadline exceeded, there is no receiver

            // This case will prevent goroutine blocking forever

            return

        }

    }()


    select {

    case <-ctx.Done():

        return "", ctx.Err()

    case result := <-ch:

        return result, nil

    }

}


func main() {

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)

    defer cancel()


    fmt.Printf("[%v] Begin make request \n", time.Now())

    abc, err := makeHTTPRequest(ctx)

    if err != nil {

        fmt.Printf("[%v] Return error: %v \n", time.Now(), err)

        return

    }

    fmt.Printf("[%v] %s", time.Now(), abc)

}


查看完整回答
反對 回復 2022-08-01
?
慕標5832272

TA貢獻1966條經(jīng)驗 獲得超4個贊

如果我沒看錯的話。有兩個問題。

  1. 你想知道為什么main()函數(shù)不起作用嗎?

  2. 最佳實踐是什么?

第 1 季度

main()在 makeHTTPRequest 中被阻止,在此期間,上下文有超時。因此,不能按預期工作。

第 2 季度

個例子可以回答你。在 中,您的代碼已經(jīng)是最佳做法。main_1()


查看完整回答
反對 回復 2022-08-01
  • 2 回答
  • 0 關注
  • 209 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號