Home > Backend Development > Golang > How Can I Customize Timeouts for HTTP GET Requests in Golang?

How Can I Customize Timeouts for HTTP GET Requests in Golang?

DDD
Release: 2024-12-08 17:15:16
Original
916 people have browsed it

How Can I Customize Timeouts for HTTP GET Requests in Golang?

Customizing Timeouts for HTTP GET Requests in Golang

When working with URL fetchers, controlling the timeout of HTTP GET requests is essential to optimize performance. By default, these requests have a long timeout, which can significantly slow down your program. Here's how you can set a custom timeout for each HTTP GET request in Golang:

Solution:

In Golang version 1.3 and later, the http.Client struct offers a Timeout field that allows you to specify a timeout duration. Here's an example:

import (
    "net/http"
    "time"
)

client := http.Client{
    Timeout: 40 * time.Second,
}

resp, fetch_err := client.Get(url)
Copy after login

By setting the Timeout field to 40 * time.Second, the HTTP GET request will time out after 40 seconds. If the request exceeds this timeout, it will return an error with the message "request timed out." This allows your URL fetcher to proceed to the next URL without being held up by slow responses.

The above is the detailed content of How Can I Customize Timeouts for HTTP GET Requests in Golang?. 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