CodexBloom - Programming Q&A Platform

Handling HTTP request timeouts in Go with context and net/http

πŸ‘€ Views: 54 πŸ’¬ Answers: 1 πŸ“… Created: 2025-05-31
go http context timeout Go

I've been banging my head against this for hours... I'm working on a Go application using version 1.20 that makes HTTP requests to an external API. I want to implement a timeout mechanism to ensure that my application doesn't hang indefinitely if the API is unresponsive. I attempted to use the `context` package to set a deadline for the request, but I keep running into issues where the timeout doesn't seem to be applied correctly. Here’s the code snippet I’m currently using: ```go package main import ( "context" "fmt" "net/http" "time" ) func main() { // Setting a timeout of 2 seconds ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, "GET", "https://httpbin.org/delay/3", nil) if err != nil { fmt.Println("behavior creating request:", err) return } client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("Request failed:", err) return } defer resp.Body.Close() fmt.Println("Response status:", resp.Status) } ``` Despite setting the timeout to 2 seconds, I noticed that the response still hangs until the external service responds, which can take longer than expected. I receive the behavior: ``` Request failed: context deadline exceeded ``` It seems like the context is not being respected as I anticipated. I’ve also experimented with increasing the timeout duration to see if that changes anything, but I'm still working with the same scenario. Is there a better way to handle timeouts in this scenario, or am I missing something in my implementation? Any insights would be greatly appreciated! I'm working on a CLI tool that needs to handle this. Any help would be greatly appreciated!