Best practices for timeout management in Go language http.Transport

WBOY
Release: 2023-07-23 12:18:20
Original
1202 people have browsed it

Best Practices for Timeout Management in Go Language http.Transport

Introduction:
When using Go language to make network requests, it is very important to set the timeout reasonably to avoid blocking of requests and resources. of waste. This article will introduce the best practices of using http.Transport for timeout management in Go language, and provide some sample code for reference.

  1. Set timeout:
    Before sending a request using http.Transport, we can use some methods to set the request timeout. For example, we can use the Timeout field of the http.Client structure to set the timeout for the entire request, for example:

    client := &http.Client{
     Timeout: time.Second * 10, // 设置超时时间为10秒
    }
    Copy after login

    In the above code, Timeout# The ## field indicates that the timeout of the entire request is 10 seconds. When the processing time of the request exceeds 10 seconds, the request will return a net.DialTimeout error.

In addition, we can also use the

Timeout of http.Request before sending the request using http.Transport field to set the timeout for a single request. For example:

req, err := http.NewRequest("GET", "http://example.com", nil)
if err != nil {
    log.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "MyClient/1.0")
req.Timeout = time.Second * 5 // 设置单个请求的超时时间为5秒

resp, err := client.Do(req)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatal(err)
}

fmt.Println(string(body))
Copy after login

In the above code, we set the timeout of a single request to 5 seconds through

req.Timeout. When the processing time of the request exceeds 5 seconds, the request will return A net.DialTimeout error.

  1. Timeout processing:

    When a request times out, we should handle this error reasonably. A common way is to use the
    context package to control request timeouts. We can create a context.Context with a timeout and pass it to the request's http.Request. For example:

    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    defer cancel()
    
    req, err := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil)
    if err != nil {
     log.Fatal(err)
    }
    Copy after login

    In the above code, we create a

    context.Context with a 10-second timeout through context.WithTimeout, and use http .NewRequestWithContext passes the Context to the request.

When sending a request, we can use

context.Context to monitor timeout events. For example:

resp, err := client.Do(req.WithContext(ctx))
if err != nil {
   if err == context.DeadlineExceeded {
       log.Println("请求超时")
       return
   }
   log.Fatal(err)
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatal(err)
}

fmt.Println(string(body))
Copy after login
In the above code, when a request timeout occurs, we will handle the timeout event by determining whether the error type is

context.DeadlineExceeded. If it is a timeout event, we can do some corresponding processing operations, such as returning error information or retrying the request.

Summary:

When using Go language to make network requests, it is very important to set a reasonable timeout. This article introduces best practices for timeout management using http.Transport in Go language and provides some sample code. By setting the timeout appropriately and using context.Context to monitor timeout events, we can better manage request timeouts and improve the stability and reliability of the program.

References:

    https://golang.org/pkg/net/http/
  • https://golang.org/pkg/net/ http/#Client
  • https://golang.org/pkg/context/
  • https://github.com/dgrijalva/jwt-go

The above is the detailed content of Best practices for timeout management in Go language http.Transport. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template