From 81a2b006d0039e320aa8835da61ab9288e386b95 Mon Sep 17 00:00:00 2001 From: Mark Laing Date: Thu, 26 May 2022 13:24:59 +0100 Subject: [PATCH] controller: Allow setting the http.Client when creating a controller. Adds a HTTPClient field to ControllerArgs and sets the client.HTTPClient to the given value. If no http client is provided, the gomaasapi.Client will instantiate it's own client per request. Signed-off-by: Mark Laing --- controller.go | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/controller.go b/controller.go index 71821ed..e13b17d 100644 --- a/controller.go +++ b/controller.go @@ -41,8 +41,9 @@ var ( // ControllerArgs is an argument struct for passing the required parameters // to the NewController method. type ControllerArgs struct { - BaseURL string - APIKey string + BaseURL string + APIKey string + HTTPClient *http.Client } // NewController creates an authenticated client to the MAAS API, and @@ -59,7 +60,7 @@ func NewController(args ControllerArgs) (Controller, error) { if !supportedVersion(apiVersion) { return nil, NewUnsupportedVersionError("version %s", apiVersion) } - return newControllerWithVersion(base, apiVersion, args.APIKey) + return newControllerWithVersion(base, apiVersion, args.APIKey, args.HTTPClient) } return newControllerUnknownVersion(args) } @@ -73,7 +74,7 @@ func supportedVersion(value string) bool { return false } -func newControllerWithVersion(baseURL, apiVersion, apiKey string) (Controller, error) { +func newControllerWithVersion(baseURL, apiVersion, apiKey string, httpClient *http.Client) (Controller, error) { major, minor, err := version.ParseMajorMinor(apiVersion) // We should not get an error here. See the test. if err != nil { @@ -89,6 +90,8 @@ func newControllerWithVersion(baseURL, apiVersion, apiKey string) (Controller, e // is an unexpected error and return now. return nil, NewUnexpectedError(err) } + + client.HTTPClient = httpClient controllerVersion := version.Number{ Major: major, Minor: minor, @@ -111,7 +114,7 @@ func newControllerUnknownVersion(args ControllerArgs) (Controller, error) { // some time in the future, we will try the most up to date version and then // work our way backwards. for _, apiVersion := range supportedAPIVersions { - controller, err := newControllerWithVersion(args.BaseURL, apiVersion, args.APIKey) + controller, err := newControllerWithVersion(args.BaseURL, apiVersion, args.APIKey, args.HTTPClient) switch { case err == nil: return controller, nil