Home > Article > Backend Development > golang http request timeout
When writing HTTP applications in Golang, due to the instability of the network environment, we may encounter the problem of HTTP request timeout.
This article will introduce how to set HTTP request timeout in Golang to prevent blocking and infinite waiting.
HTTP request timeout means that the client waits for a response after sending a request to the server for more than the predetermined time, causing the request to be cancelled. This situation generally occurs under network delay, high load, insufficient server resources, etc.
For HTTP applications in Golang, when there is no response or a request that takes too long to respond, in order to prevent the application from blocking and waiting indefinitely, we need to set the HTTP request timeout.
In a Golang application, each HTTP request is a goroutine, which will send the request in the network and wait for the response. If the request timeout is not set, it may cause the program to block and enter an infinite loop while waiting for a response, increasing the load on the server and reducing performance.
Additionally, if there are malicious users or attackers in the application, they may send fake requests to make the application wait for a long time for a response, thus exhausting server resources.
Therefore, setting the HTTP request timeout can ensure that too much time and resources are not wasted before receiving a response, and prevent the application from being attacked and running out of resources.
In Golang, we can use the net/http library to send HTTP requests and set the timeout. The Client type defined in this library has a Timeout property that allows you to set a timeout.
The following is the sample code:
package main import ( "fmt" "net/http" "time" ) func main() { client := http.Client{ Timeout: time.Second * 5, // 设置超时时间为5秒 } req, err := http.NewRequest(http.MethodGet, "https://www.example.com", nil) if err != nil { panic(err) } res, err := client.Do(req) if err != nil { panic(err) } fmt.Println(res) }
In this sample code, we create an HTTP client and set the timeout to 5 seconds. We then send a GET request to https://www.example.com and wait for the response. If the request times out or the response takes too long, it will end within 5 seconds.
In the above sample code, we use the panic function to handle HTTP request timeout errors. However, in real applications, more reliable methods should be used to handle timeout errors.
The following is a more reliable method: add a Context to the request and use a select statement to handle timeouts and normal responses:
package main import ( "context" "fmt" "net/http" "time" ) func main() { client := http.Client{ Timeout: time.Second * 5, // 设置超时时间为5秒 } req, err := http.NewRequest(http.MethodGet, "https://www.example.com", nil) if err != nil { panic(err) } ctx, cancel := context.WithTimeout(req.Context(), time.Second*5) defer cancel() // 在函数退出时取消Context req = req.WithContext(ctx) // 使用带有超时的Context创建新请求 resp, err := client.Do(req) if err != nil { select { case <-ctx.Done(): // 超时错误 fmt.Println("Request timed out") default: // 其他错误 panic(err) } } defer resp.Body.Close() fmt.Println(resp.StatusCode) }
In this sample code, we create a Context, And used the WithTimeout function to set the timeout. Then we create a new request using a Context with a timeout and send this request.
If the request times out or other errors occur, different handling methods will be adopted based on different error types. This allows us to have more control over the application and handle error situations gracefully.
When writing HTTP applications in Golang, in order to avoid blocking and infinite waiting, it is very important to set the HTTP request timeout. We can set the timeout using the Client type from the net/http library. And use Context and select statements to handle timeout errors and other errors.
When writing high-performance and stable applications, you should set an appropriate timeout based on the actual situation. This will ensure that the application can still work properly in uncontrolled environments.
The above is the detailed content of golang http request timeout. For more information, please follow other related articles on the PHP Chinese website!