golang http request timeout 幾種方式

1. 

client := http.Client{
    Timeout: time.Duration(2 * time.Second),
}

2. 

timeout := time.Duration(10 * time.Microsecond)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
request, _ := http.NewRequest("POST", "localhost:3003/v1/api/sign_in", bytes.NewBuffer(jsonData))

 request.WithContent(ctx)

 

3.

resultChan := make(chan string, 1)
go RequestApi(resultChan)

select {
case <- time.After(100 * time.Microsecond):
    fmt.Println("timeout")
case res := <- resultChan:
    fmt.Println(res)
}
time.Sleep(time.Second * 3)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章