Golang goroutine-safe http client with different timeout?


Suppose I have the following function:

func SendRequest(c *Client, timeout time.Duration) {
  if timeout > 0 {
    c.Timeout = timeout
  } else {
    c.Timeout = defaultTimeout

I want to allow multiple go-routines to call this function (to share the same HTTP client), but the way this is written apparently can’t guarantee goroutine safety. (Also changing the timeout of the client passed in is weird too…)

I’m not sure what’s the best way to do this. Should I use different client for different timeouts? Should I use some mutex? Or in general how do I share a HTTP client with different timeouts?



You need to use different Clients. Even if you protect your function with a mutex, you can’t protect the internal access by the Client, and another goroutine could change it while making the request.

Multiple Clients can still share the same Transport, and they both will use the DefaultTransport if you don’t specify one.

Answered By – JimB

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.