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

Added request callback #49

Merged
merged 1 commit into from Dec 25, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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