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)

你可能感兴趣的:(golang http request timeout 几种方式)