Home > Backend Development > Golang > Request timeout settings and best practices for http.Transport in Go language

Request timeout settings and best practices for http.Transport in Go language

王林
Release: 2023-07-22 16:13:13
Original
1800 people have browsed it

Request timeout settings and best practices for http.Transport in Go language

In Go language, http.Transport is an important network request library. It provides a series of methods and options to set the request timeout to help developers better control the execution time of requests and avoid resource waste. This article explains how to set request timeouts and gives some example code for best practices.

Timeout setting method

In http.Transport, you can use the following two methods to set the request timeout:

  1. Use the Timeout field

Timeout is a field of http.Transport, type is time.Duration. By setting Timeout, you can specify the timeout for the entire request, including all processes such as establishing a connection, sending a request, and receiving a response. The example is as follows:

package main

import (
    "net/http"
    "time"
)

func main() {
    transport := &http.Transport{
        // 设置请求超时时间为5秒
        Timeout: 5 * time.Second,
    }

    client := &http.Client{
        Transport: transport,
    }

    resp, err := client.Get("http://example.com")
    if err != nil {
        // 处理错误
        return
    }

    // 处理响应
    defer resp.Body.Close()
}
Copy after login
  1. Using the Deadline field

Deadline is a field of http.Request, type is time.Time. By setting the deadline, you can set an independent timeout for a single request. Examples are as follows:

package main

import (
    "net/http"
    "time"
)

func main() {
    req, err := http.NewRequest("GET", "http://example.com", nil)
    if err != nil {
        // 处理错误
        return
    }

    // 设置请求超时时间为5秒
    req.Header.Set("Timeout", "5s")
    req = req.WithContext(http.TimeoutContext(req.Context(), 5*time.Second))

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        // 处理错误
        return
    }

    // 处理响应
    defer resp.Body.Close()
}
Copy after login

Best Practice

In actual development, we need to set the request timeout according to specific scenarios and needs. The following is sample code for several best practices:

  1. Set a global default timeout

You can set a global default timeout for all requests throughout the application time. This improves code readability and maintainability. Examples are as follows:

package main

import (
    "net/http"
    "time"
)

var client = &http.Client{
    Transport: &http.Transport{
        // 设置全局默认超时时间为10秒
        Timeout: 10 * time.Second,
    },
}

func main() {
    resp, err := client.Get("http://example.com")
    if err != nil {
        // 处理错误
        return
    }

    // 处理响应
    defer resp.Body.Close()
}
Copy after login
  1. Set different timeouts

For different requests, you can set different timeouts. For example, for different API interfaces, the timeout can be set according to the characteristics of the interface and response time requirements. An example is as follows:

package main

import (
    "net/http"
    "time"
)

func main() {
    apiA := &http.Client{
        Transport: &http.Transport{
            // 设置API A的超时时间为3秒
            Timeout: 3 * time.Second,
        },
    }

    apiB := &http.Client{
        Transport: &http.Transport{
            // 设置API B的超时时间为5秒
            Timeout: 5 * time.Second,
        },
    }

    respA, err := apiA.Get("http://apiA.example.com")
    if err != nil {
        // 处理错误
        return
    }

    respB, err := apiB.Get("http://apiB.example.com")
    if err != nil {
        // 处理错误
        return
    }

    // 处理响应
    defer respA.Body.Close()
    defer respB.Body.Close()
}
Copy after login

Summary

This article introduces how to set the request timeout of http.Transport in the Go language, and gives some best practice sample codes. In actual development, flexibly setting the request timeout according to specific needs and scenarios can improve the performance and reliability of the application.

The above is the detailed content of Request timeout settings and best practices for http.Transport in Go language. 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