From 4145fa842c2a126c45b2e9df6493e46a15b18fb3 Mon Sep 17 00:00:00 2001 From: Felix Pojtinger Date: Tue, 27 Apr 2021 20:16:33 +0200 Subject: [PATCH] Add ability to define custom interceptors (fixes #35) --- client.go | 14 ++++++++++---- requests.go | 4 ++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/client.go b/client.go index 6539c45..0d31467 100644 --- a/client.go +++ b/client.go @@ -15,9 +15,10 @@ import ( // Client defines our structure type Client struct { - root string - headers http.Header - c *http.Client + root string + headers http.Header + interceptor func(method string, rq *http.Request) + c *http.Client authMutex sync.Mutex auth Authenticator @@ -58,7 +59,7 @@ func (n *NoAuth) Authorize(req *http.Request, method string, path string) { // NewClient creates a new instance of client func NewClient(uri, user, pw string) *Client { - return &Client{FixSlash(uri), make(http.Header), &http.Client{}, sync.Mutex{}, &NoAuth{user, pw}} + return &Client{FixSlash(uri), make(http.Header), nil, &http.Client{}, sync.Mutex{}, &NoAuth{user, pw}} } // SetHeader lets us set arbitrary headers for a given client @@ -66,6 +67,11 @@ func (c *Client) SetHeader(key, value string) { c.headers.Add(key, value) } +// SetInterceptor lets us set an arbitrary interceptor for a given client +func (c *Client) SetInterceptor(interceptor func(method string, rq *http.Request)) { + c.interceptor = interceptor +} + // SetTimeout exposes the ability to set a time limit for requests func (c *Client) SetTimeout(timeout time.Duration) { c.c.Timeout = timeout diff --git a/requests.go b/requests.go index bfa1e94..df04d17 100644 --- a/requests.go +++ b/requests.go @@ -43,6 +43,10 @@ func (c *Client) req(method, path string, body io.Reader, intercept func(*http.R intercept(r) } + if c.interceptor != nil { + c.interceptor(method, r) + } + rs, err := c.c.Do(r) if err != nil { return nil, err