Add ability to define custom interceptors (fixes #35)

This commit is contained in:
Felix Pojtinger 2021-04-27 20:16:33 +02:00 committed by Christoph Polcin
parent 8244b5a5f5
commit 4145fa842c
2 changed files with 14 additions and 4 deletions

View File

@ -15,9 +15,10 @@ import (
// Client defines our structure // Client defines our structure
type Client struct { type Client struct {
root string root string
headers http.Header headers http.Header
c *http.Client interceptor func(method string, rq *http.Request)
c *http.Client
authMutex sync.Mutex authMutex sync.Mutex
auth Authenticator auth Authenticator
@ -58,7 +59,7 @@ func (n *NoAuth) Authorize(req *http.Request, method string, path string) {
// NewClient creates a new instance of client // NewClient creates a new instance of client
func NewClient(uri, user, pw string) *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 // 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) 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 // SetTimeout exposes the ability to set a time limit for requests
func (c *Client) SetTimeout(timeout time.Duration) { func (c *Client) SetTimeout(timeout time.Duration) {
c.c.Timeout = timeout c.c.Timeout = timeout

View File

@ -43,6 +43,10 @@ func (c *Client) req(method, path string, body io.Reader, intercept func(*http.R
intercept(r) intercept(r)
} }
if c.interceptor != nil {
c.interceptor(method, r)
}
rs, err := c.c.Do(r) rs, err := c.c.Do(r)
if err != nil { if err != nil {
return nil, err return nil, err