Home > Backend Development > Golang > How to Customize HTTP Request Timeouts in Go?

How to Customize HTTP Request Timeouts in Go?

Mary-Kate Olsen
Release: 2024-12-21 10:32:09
Original
637 people have browsed it

How to Customize HTTP Request Timeouts in Go?

Customizing Timeout for HTTP Requests in Go

Consider a scenario where you're building a URL fetcher in Go, with a list of URLs awaiting retrieval. You're employing http.Get() to request each URL, expecting a response. However, the default timeout for these requests can be excessive, resulting in a slow fetching process. The objective is to establish a custom timeout, approximately 40-45 seconds, after which the fetcher should report "request timed out" and proceed to the subsequent URL.

Embracing the power of Go 1.3, http.Client introduces a Timeout field. By leveraging this field, you can tailor the timeout duration to your specific needs.

Here's a code snippet to illustrate its usage:

client := http.Client{
    Timeout: 5 * time.Second,
}
client.Get(url)
Copy after login

Note that the timeout is specified as a time.Duration value of 5 seconds in this example, which can be adjusted to the desired duration of 40-45 seconds to meet your requirements. By implementing this solution, you'll improve the efficiency of your URL fetcher, ensuring timely responses and smoother operation.

The above is the detailed content of How to Customize HTTP Request Timeouts in Go?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template