From 436586e3ae7dd01aac3f85851fb3ca400a70ef18 Mon Sep 17 00:00:00 2001 From: "Daniel S. Reichenbach" Date: Sat, 16 Dec 2017 18:23:01 +0100 Subject: [PATCH] Added request callback ... allows to e.g. log request and response in Terraform provider --- lib/client.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/lib/client.go b/lib/client.go index 0f805a1..be84fae 100644 --- a/lib/client.go +++ b/lib/client.go @@ -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 @@ -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 { @@ -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 {