Skip to content

Commit

Permalink
Added request callback
Browse files Browse the repository at this point in the history
... allows to e.g. log request and response in Terraform provider
  • Loading branch information
Daniel S. Reichenbach committed Dec 16, 2017
1 parent e5dad9a commit 436586e
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,14 @@ type Client struct {

// Throttling struct
bucket *ratelimit.Bucket

// Optional function called after every successful request made to the API
onRequestCompleted RequestCompletionCallback
}

// RequestCompletionCallback defines the type of the request callback function
type RequestCompletionCallback func(*http.Request, *http.Response)

// Options represents optional settings and flags that can be passed to NewClient
type Options struct {
// HTTP client for communication with the Vultr API
Expand Down Expand Up @@ -143,6 +149,11 @@ func (c *Client) post(path string, values url.Values, data interface{}) error {
return c.do(req, data)
}

// OnRequestCompleted sets the API request completion callback
func (c *Client) OnRequestCompleted(rc RequestCompletionCallback) {
c.onRequestCompleted = rc
}

func (c *Client) newRequest(method string, path string, body io.Reader) (*http.Request, error) {
relPath, err := url.Parse(apiKeyPath(path, c.APIKey))
if err != nil {
Expand Down Expand Up @@ -193,6 +204,10 @@ func (c *Client) do(req *http.Request, data interface{}) error {
return err
}

if c.onRequestCompleted != nil {
c.onRequestCompleted(req, resp)
}

body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
Expand Down

0 comments on commit 436586e

Please sign in to comment.