Skip to content

Commit

Permalink
feat: execute request and response interceptors.
Browse files Browse the repository at this point in the history
  • Loading branch information
ghosind committed Nov 8, 2023
1 parent d0cf3de commit ebde5c1
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
36 changes: 36 additions & 0 deletions interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,39 @@ type RequestInterceptor func(*http.Request) error

// ResponseInterceptor is a function to intercept the responses.
type ResponseInterceptor func(*http.Response) error

// doRequestIntercept executes the request interceptors, it'll terminate if the interceptor
// function returns an error.
func (cli *Client) doRequestIntercept(req *http.Request) error {
interceptors := cli.reqInterceptors
if len(interceptors) == 0 {
return nil
}

for _, interceptor := range interceptors {
err := interceptor(req)
if err != nil {
return err
}
}

return nil
}

// doResponseIntercept executes the response interceptors, it'll terminate if the interceptor
// function returns an error.
func (cli *Client) doResponseIntercept(resp *http.Response) error {
interceptors := cli.respInterceptors
if len(interceptors) == 0 {
return nil
}

for _, interceptor := range interceptors {
err := interceptor(resp)
if err != nil {
return err
}
}

return nil
}
26 changes: 25 additions & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,38 @@ func (cli *Client) request(method, url string, opts ...RequestOptions) (*http.Re
}
defer canFunc()

resp, err := cli.sendRequest(req, opt)
resp, err := cli.sendRequestWithInterceptors(req, opt)
if err != nil {
return resp, err
}

return cli.handleResponse(resp, opt)
}

// sendRequestWithInterceptors tries to execute the request and response interceptors and
// sends the request.
func (cli *Client) sendRequestWithInterceptors(
req *http.Request,
opt RequestOptions,
) (*http.Response, error) {
err := cli.doRequestIntercept(req)
if err != nil {
return nil, err
}

resp, err := cli.sendRequest(req, opt)
if err != nil {
return nil, err
}

err = cli.doResponseIntercept(resp)
if err != nil {
return resp, err
}

return resp, nil
}

// sendRequest gets an HTTP client from the HTTP clients pool and sends the request. It tries to
// re-send the request when it fails to make the request and the number of attempts is less than
// the maximum limitation.
Expand Down

0 comments on commit ebde5c1

Please sign in to comment.