Home  >  Article  >  Backend Development  >  http client: faster timeout when no network

http client: faster timeout when no network

WBOY
WBOYforward
2024-02-11 12:09:09690browse

http client: faster timeout when no network

#php editor Xinyi today introduces to you a tool called "http client: faster timeout when there is no network". In an unstable or non-network environment, a long timeout may result in poor user experience. This http client tool can help solve this problem. It optimizes the timeout mechanism to make the timeout faster when there is no network, thus improving the application response speed and user experience. Let’s take a look at the specific functions and usage of this tool!

Question content

When making an http get request in go, even if there is no network connection, it will wait for the full timeout before returning an error.

I think internally it knows it failed very quickly; I want the error to propagate as quickly as possible rather than waiting for a timeout. I do want it to try for 20 seconds while the network is present but slow. How do I set up a client with this behavior?

View the code of the problem:

var client = &http.Client{
    Timeout: time.Second * 20,
}

response, err := client.Get(url)

If it matters, I'm using gomobile and it's running on the ios simulator.

Solution

The answer here is very simple: internally golang can and does know when there is no network, and propagates the failure promptly without waiting for the 20 second timeout. Nothing is sent over the network and there is no waiting. Everything seems to be working fine in Go and no changes to the sample code are required.

The problem still keeps reoccurring, but only in the iOS simulator. This appears to be an issue specific to how the iOS simulator maps connections to the host operating system. Not sure if this is a long-standing issue or a one-off issue with my MacOS/emulator pairing. On host MacOS and real iOS devices it works fine, when there is no network interface it times out immediately.

No additional requests are needed as this is just another path to the same conclusion, which increases the likelihood of other failures. Might help distinguish network problems from problems with a specific service, or get a faster indicator of the true network status (after the connected network interface exists).

The above is the detailed content of http client: faster timeout when no network. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete