Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix race condition during request: Protect pre/post request hooks with RWMutex #597

Merged
merged 2 commits into from
Mar 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,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 @@ -417,7 +419,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 @@ -431,7 +437,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 @@ -935,6 +945,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