CodexBloom - Programming Q&A Platform

Golang: Issues with Timeouts in HTTP Client when Using Custom Transport

đź‘€ Views: 24 đź’¬ Answers: 1 đź“… Created: 2025-06-13
golang http timeout transport Go

I'm upgrading from an older version and I've encountered a strange issue with I'm encountering unexpected behavior with my Golang HTTP client when I configure a custom transport. Specifically, I have the following setup where I want to implement a custom transport to log requests and their durations. However, I'm noticing that the timeout I set seems to not be honored during requests, leading to long waits on unresponsive servers. Here’s the code I’m using: ```go package main import ( "context" "fmt" "log" "net/http" "time" ) type LoggingTransport struct { Transport http.RoundTripper } func (lt *LoggingTransport) RoundTrip(req *http.Request) (*http.Response, error) { start := time.Now() resp, err := lt.Transport.RoundTrip(req) duration := time.Since(start) log.Printf("Request to %s took %s", req.URL, duration) return resp, err } func main() { client := &http.Client{ Transport: &LoggingTransport{ Transport: http.DefaultTransport, }, Timeout: 2 * time.Second, } ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil) if err != nil { log.Fatalf("Error creating request: %v", err) } resp, err := client.Do(req) if err != nil { log.Fatalf("Error making request: %v", err) } defer resp.Body.Close() fmt.Println("Response status:", resp.Status) } ``` When testing with a purposely slow server, I expect the request to timeout after 2 seconds due to the client’s timeout setting, but instead, it waits indefinitely. I've confirmed that the request context’s timeout is set to 1 second, which should ideally cause it to cancel. However, it seems that the HTTP client’s timeout isn't being respected. I tried changing the `Transport` to `http.DefaultTransport` and even implementing my own timeout logic within the `RoundTrip` method, but nothing seems to help. I’ve also checked that I’m using Go version 1.20.4, which should have the necessary timeout handling. Any insights on why the client timeout isn’t being applied correctly in this scenario? Am I missing something in the transport implementation or the request context usage? I'm working on a API that needs to handle this. Any ideas what could be causing this? I recently upgraded to Go 3.11. How would you solve this? I'm coming from a different tech stack and learning Go. I'd be grateful for any help.