How to set a timeout for http.Get() in Golang?
Hello everyone! I'm new to Go and encountered a problem when making HTTP requests.\n\nI need to send GET requests to an external API, but sometimes the server hangs or responds very slowly. In the standard example from the documentation, I use `http.Get()`, and it just hangs indefinitely, blocking the entire program. Here's my code:\n\n```go\nresp, err := http.Get("https://api.example.com/data")\nif err != nil {\n log.Fatal(err)\n}\ndefer resp.Body.Close()\n```\n\nThe problem is that if the server doesn't respond, the program hangs forever. I want to set a timeout, for example, 5 seconds, so that if there's no response, the program returns an error and continues.\n\nI tried looking in the documentation, but I didn't find a simple way to add a timeout to `http.Get()`. I saw something about `http.Client`, but I didn't understand how
No answers yet.
Log in to leave an answer