diff --git a/environment.go b/environment.go index afdbcfb7..f99093ae 100644 --- a/environment.go +++ b/environment.go @@ -12,6 +12,7 @@ type Environment struct { SiteName string ChargebeeDomain string Protocol string + HttpClient *http.Client } var ( @@ -32,9 +33,14 @@ func Configure(key string, siteName string) { } DefaultEnv = Environment{Key: key, SiteName: siteName} } + func WithHTTPClient(c *http.Client) { - httpClient = c + // I don't really like setting this on the default environment, but maintains + // backwards compatibility at least while having the ability for client to be + // configured differently. + DefaultEnv.HttpClient = c } + func (env *Environment) apiBaseUrl() string { if env.Protocol == "" { env.Protocol = "https" diff --git a/http_request.go b/http_request.go index 68a5d592..f8375714 100644 --- a/http_request.go +++ b/http_request.go @@ -7,11 +7,32 @@ import ( "net/http" ) -var httpClient = &http.Client{Timeout: DefaultHTTPTimeout} +// RequestOption allows you to pass along functions that customize a +// RequestOptions struct. +type RequestOption func(*RequestOptions) + +// HTTPOption contains a struct of various request options that could be +//customized. +type RequestOptions struct { + client *http.Client +} + +// Client allows you to customize the http client on a per-request basis +func SetClient(hc *http.Client) RequestOption { + return func(h *RequestOptions) { + h.client = hc + } +} //Do is used to execute an API Request. -func Do(req *http.Request) (string, error) { - response, err := httpClient.Do(req) +func Do(req *http.Request, opts ...RequestOption) (string, error) { + reqOpts := RequestOptions{ + client: &http.Client{}, + } + for _, o := range opts { + o(&reqOpts) + } + response, err := reqOpts.client.Do(req) if err != nil { return "", err } diff --git a/list_request.go b/list_request.go index 0ed42200..a8685405 100644 --- a/list_request.go +++ b/list_request.go @@ -10,7 +10,11 @@ func (request RequestObj) ListRequestWithEnv(env Environment) (*ResultList, erro if err != nil { panic(err) } - res, err1 := Do(req) + opts := []RequestOption{} + if env.HttpClient != nil { + opts = append(opts, SetClient(env.HttpClient)) + } + res, err1 := Do(req, opts...) result := &ResultList{} if err1 != nil { return result, err1 diff --git a/request.go b/request.go index f6639c37..cd4f9c4f 100644 --- a/request.go +++ b/request.go @@ -17,7 +17,11 @@ func (request RequestObj) RequestWithEnv(env Environment) (*Result, error) { if err != nil { panic(err) } - res, err1 := Do(req) + opts := []RequestOption{} + if env.HttpClient != nil { + opts = append(opts, SetClient(env.HttpClient)) + } + res, err1 := Do(req, opts...) result := &Result{} if err1 != nil { return result, err1