4
0

poolhttp.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package poolhttp
  2. import (
  3. "net/http"
  4. "sync"
  5. "github.com/smallstep/certificates/internal/httptransport"
  6. )
  7. // Transporter is implemented by custom HTTP clients with a method that
  8. // returns an [*http.Transport].
  9. type Transporter interface {
  10. Transport() *http.Transport
  11. }
  12. // Client is an HTTP client that uses a [sync.Pool] to create new and reuse HTTP
  13. // clients. It implements the [provisioner.HTTPClient] and [Transporter]
  14. // interfaces. This is the HTTP client used by the provisioners.
  15. type Client struct {
  16. rw sync.RWMutex
  17. pool sync.Pool
  18. }
  19. // New creates a new poolhttp [Client], the [sync.Pool] will initialize a new
  20. // [*http.Client] with the given function.
  21. func New(fn func() *http.Client) *Client {
  22. return &Client{
  23. pool: sync.Pool{
  24. New: func() any { return fn() },
  25. },
  26. }
  27. }
  28. // SetNew replaces the inner pool with a new [sync.Pool] with the given New
  29. // function. This method can be use concurrently with other methods of this
  30. // package.
  31. func (c *Client) SetNew(fn func() *http.Client) {
  32. c.rw.Lock()
  33. c.pool = sync.Pool{
  34. New: func() any { return fn() },
  35. }
  36. c.rw.Unlock()
  37. }
  38. // getClient gets a client from the pool.
  39. func (c *Client) getClient() *http.Client {
  40. c.rw.RLock()
  41. defer c.rw.RUnlock()
  42. if hc, ok := c.pool.Get().(*http.Client); ok && hc != nil {
  43. return hc
  44. }
  45. return nil
  46. }
  47. // Get issues a GET request to the specified URL. If the response is one of the
  48. // following redirect codes, Get follows the redirect after calling the
  49. // [Client.CheckRedirect] function:
  50. func (c *Client) Get(u string) (resp *http.Response, err error) {
  51. if hc := c.getClient(); hc != nil {
  52. resp, err = hc.Get(u)
  53. c.pool.Put(hc)
  54. } else {
  55. resp, err = http.DefaultClient.Get(u)
  56. }
  57. return
  58. }
  59. // Do sends an HTTP request and returns an HTTP response, following policy (such
  60. // as redirects, cookies, auth) as configured on the client.
  61. func (c *Client) Do(req *http.Request) (resp *http.Response, err error) {
  62. if hc := c.getClient(); hc != nil {
  63. resp, err = hc.Do(req)
  64. c.pool.Put(hc)
  65. } else {
  66. resp, err = http.DefaultClient.Do(req)
  67. }
  68. return
  69. }
  70. // Transport() returns a clone of the http.Client Transport or returns the
  71. // default transport.
  72. func (c *Client) Transport() *http.Transport {
  73. if hc := c.getClient(); hc != nil {
  74. tr, ok := hc.Transport.(*http.Transport)
  75. c.pool.Put(hc)
  76. if ok {
  77. return tr.Clone()
  78. }
  79. }
  80. return httptransport.New()
  81. }