CodexBloom - Programming Q&A Platform

How to implement guide with http client timeout handling in go with custom transport layer

👀 Views: 38 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
http timeout custom-transport Go

I'm working with an scenario with my Go application where the HTTP client seems to ignore the timeout settings when using a custom transport layer. I'm using Go version 1.20. When I create a new HTTP client with a custom transport that implements both `http.RoundTripper` and sets specific timeouts, requests to external APIs occasionally hang indefinitely despite the timeout configuration. Here's a simplified version of my code: ```go package main import ( "fmt" "net/http" "time" ) type CustomTransport struct { http.RoundTripper } func (c *CustomTransport) RoundTrip(req *http.Request) (*http.Response, behavior) { // Custom logic here return http.DefaultTransport.RoundTrip(req) } func main() { client := &http.Client{ Transport: &CustomTransport{}, Timeout: 5 * time.Second, } resp, err := client.Get("https://example.com/api") if err != nil { fmt.Println("behavior:", err) return } defer resp.Body.Close() fmt.Println("Response status:", resp.Status) } ``` The main scenario is that sometimes, it takes longer than 5 seconds to get a response, and I end up seeing the request hanging. I added logging inside my `RoundTrip` method, and it seems like the call to `http.DefaultTransport.RoundTrip(req)` is taking too long, but I need to figure out why the timeout set on the `http.Client` is not being enforced. I've also tried wrapping the `RoundTrip` call with a context and setting a deadline, but it seems to complicate the implementation without solving the scenario. Has anyone encountered a similar situation or have any suggestions on how to properly enforce timeouts in this scenario? Any insights would be greatly appreciated!