Skip to content

Commit

Permalink
Protect pre/post request hooks with RWMutex to mitigate race conditio…
Browse files Browse the repository at this point in the history
…ns (#597)

Co-authored-by: Jeevanandam M <jeeva@myjeeva.com>
  • Loading branch information
jameshoulahan and jeevatkm committed Mar 8, 2023
1 parent 5ebbbb1 commit 1578007
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,11 @@ type Client struct {
proxyURL *url.URL
beforeRequest []RequestMiddleware
udBeforeRequest []RequestMiddleware
udBeforeRequestLock sync.RWMutex
preReqHook PreRequestHook
successHooks []SuccessHook
afterResponse []ResponseMiddleware
afterResponseLock sync.RWMutex
requestLog RequestLogCallback
responseLog ResponseLogCallback
errorHooks []ErrorHook
Expand Down Expand Up @@ -432,7 +434,11 @@ func (c *Client) NewRequest() *Request {
// return nil // if its success otherwise return error
// })
func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client {
c.udBeforeRequestLock.Lock()
defer c.udBeforeRequestLock.Unlock()

c.udBeforeRequest = append(c.udBeforeRequest, m)

return c
}

Expand All @@ -447,7 +453,11 @@ func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client {
// return nil // if its success otherwise return error
// })
func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client {
c.afterResponseLock.Lock()
defer c.afterResponseLock.Unlock()

c.afterResponse = append(c.afterResponse, m)

return c
}

Expand Down Expand Up @@ -978,6 +988,14 @@ func (c *Client) GetClient() *http.Client {
// Executes method executes the given `Request` object and returns response
// error.
func (c *Client) execute(req *Request) (*Response, error) {
// Lock the user-defined pre-request hooks.
c.udBeforeRequestLock.RLock()
defer c.udBeforeRequestLock.RUnlock()

// Lock the post-request hooks.
c.afterResponseLock.RLock()
defer c.afterResponseLock.RUnlock()

// Apply Request middleware
var err error

Expand Down

0 comments on commit 1578007

Please sign in to comment.