dongzuo7166 2015-07-11 16:02
浏览 45
已采纳

Golang Goroutine安全的http客户端具有不同的超时时间?

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?

Thanks!

  • 写回答

1条回答 默认 最新

  • download1214 2015-07-11 17:18
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?