diff --git a/client.go b/client.go index 28433b766..4ac274b50 100644 --- a/client.go +++ b/client.go @@ -3,6 +3,8 @@ package linodego import ( "bytes" "context" + "crypto/tls" + "crypto/x509" "encoding/json" "fmt" "io" @@ -14,13 +16,12 @@ import ( "path/filepath" "reflect" "regexp" + "runtime" "strconv" "strings" "sync" "text/template" "time" - - "github.com/go-resty/resty/v2" ) const ( @@ -49,7 +50,6 @@ const ( APIDefaultCacheExpiration = time.Minute * 15 ) -//nolint:unused var ( reqLogTemplate = template.Must(template.New("request").Parse(`Sending request: Method: {{.Method}} @@ -63,20 +63,35 @@ Headers: {{.Headers}} Body: {{.Body}}`)) ) +type RequestLog struct { + Method string + URL string + Headers http.Header + Body string +} + +type ResponseLog struct { + Method string + URL string + Headers http.Header + Body string +} + var envDebug = false -// Client is a wrapper around the Resty client +// Client is a wrapper around the http client type Client struct { - resty *resty.Client - userAgent string - debug bool - retryConditionals []RetryConditional + httpClient *http.Client + userAgent string + debug bool pollInterval time.Duration baseURL string apiVersion string apiProto string + hostURL string + header http.Header selectedProfile string loadedProfile string @@ -87,6 +102,16 @@ type Client struct { cacheExpiration time.Duration cachedEntries map[string]clientCacheEntry cachedEntryLock *sync.RWMutex + logger Logger + requestLog func(*RequestLog) error + onBeforeRequest []func(*http.Request) error + onAfterResponse []func(*http.Response) error + + retryConditionals []RetryConditional + retryMaxWaitTime time.Duration + retryMinWaitTime time.Duration + retryAfter RetryAfter + retryCount int } type EnvDefaults struct { @@ -103,13 +128,11 @@ type clientCacheEntry struct { } type ( - Request = resty.Request - Response = resty.Response - Logger = resty.Logger + Request = http.Request + Response = http.Response ) func init() { - // Whether we will enable Resty debugging output if apiDebug, ok := os.LookupEnv("LINODE_DEBUG"); ok { if parsed, err := strconv.ParseBool(apiDebug); err == nil { envDebug = parsed @@ -123,7 +146,7 @@ func init() { // SetUserAgent sets a custom user-agent for HTTP requests func (c *Client) SetUserAgent(ua string) *Client { c.userAgent = ua - c.resty.SetHeader("User-Agent", c.userAgent) + c.SetHeader("User-Agent", c.userAgent) return c } @@ -135,8 +158,8 @@ type RequestParams struct { // Generic helper to execute HTTP requests using the net/http package // -// nolint:unused, funlen, gocognit -func (c *httpClient) doRequest(ctx context.Context, method, url string, params RequestParams) error { +// nolint:funlen, gocognit +func (c *Client) doRequest(ctx context.Context, method, endpoint string, params RequestParams, paginationMutator *func(*http.Request) error) error { var ( req *http.Request bodyBuffer *bytes.Buffer @@ -144,8 +167,8 @@ func (c *httpClient) doRequest(ctx context.Context, method, url string, params R err error ) - for range httpDefaultRetryCount { - req, bodyBuffer, err = c.createRequest(ctx, method, url, params) + for range c.retryCount { + req, bodyBuffer, err = c.createRequest(ctx, method, endpoint, params) if err != nil { return err } @@ -154,8 +177,17 @@ func (c *httpClient) doRequest(ctx context.Context, method, url string, params R return err } + if paginationMutator != nil { + if err := (*paginationMutator)(req); err != nil { + if c.debug && c.logger != nil { + c.logger.Errorf("failed to mutate before request: %v", err) + } + return fmt.Errorf("failed to mutate before request: %w", err) + } + } + if c.debug && c.logger != nil { - c.logRequest(req, method, url, bodyBuffer) + c.logRequest(req, method, endpoint, bodyBuffer) } processResponse := func() error { @@ -214,33 +246,33 @@ func (c *httpClient) doRequest(ctx context.Context, method, url string, params R return err } -// nolint:unused -func (c *httpClient) shouldRetry(resp *http.Response, err error) bool { +func (c *Client) shouldRetry(resp *http.Response, err error) bool { for _, retryConditional := range c.retryConditionals { if retryConditional(resp, err) { + log.Printf("[INFO] Received error %v - Retrying", err) return true } } return false } -// nolint:unused -func (c *httpClient) createRequest(ctx context.Context, method, url string, params RequestParams) (*http.Request, *bytes.Buffer, error) { +func (c *Client) createRequest(ctx context.Context, method, endpoint string, params RequestParams) (*http.Request, *bytes.Buffer, error) { var bodyReader io.Reader var bodyBuffer *bytes.Buffer if params.Body != nil { - bodyBuffer = new(bytes.Buffer) - if err := json.NewEncoder(bodyBuffer).Encode(params.Body); err != nil { + var ok bool + bodyReader, ok = params.Body.(io.Reader) + if !ok { if c.debug && c.logger != nil { - c.logger.Errorf("failed to encode body: %v", err) + c.logger.Errorf("failed to read body: params.Body is not an io.Reader") } - return nil, nil, fmt.Errorf("failed to encode body: %w", err) + return nil, nil, fmt.Errorf("failed to read body: params.Body is not an io.Reader") } - bodyReader = bodyBuffer } - req, err := http.NewRequestWithContext(ctx, method, url, bodyReader) + req, err := http.NewRequestWithContext(ctx, method, fmt.Sprintf("%s/%s", strings.TrimRight(c.hostURL, "/"), + strings.TrimLeft(endpoint, "/")), bodyReader) if err != nil { if c.debug && c.logger != nil { c.logger.Errorf("failed to create request: %v", err) @@ -248,17 +280,24 @@ func (c *httpClient) createRequest(ctx context.Context, method, url string, para return nil, nil, fmt.Errorf("failed to create request: %w", err) } + // Set the default headers req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") if c.userAgent != "" { req.Header.Set("User-Agent", c.userAgent) } + // Set additional headers added to the client + for name, values := range c.header { + for _, value := range values { + req.Header.Set(name, value) + } + } + return req, bodyBuffer, nil } -// nolint:unused -func (c *httpClient) applyBeforeRequest(req *http.Request) error { +func (c *Client) applyBeforeRequest(req *http.Request) error { for _, mutate := range c.onBeforeRequest { if err := mutate(req); err != nil { if c.debug && c.logger != nil { @@ -267,11 +306,11 @@ func (c *httpClient) applyBeforeRequest(req *http.Request) error { return fmt.Errorf("failed to mutate before request: %w", err) } } + return nil } -// nolint:unused -func (c *httpClient) applyAfterResponse(resp *http.Response) error { +func (c *Client) applyAfterResponse(resp *http.Response) error { for _, mutate := range c.onAfterResponse { if err := mutate(resp); err != nil { if c.debug && c.logger != nil { @@ -283,8 +322,7 @@ func (c *httpClient) applyAfterResponse(resp *http.Response) error { return nil } -// nolint:unused -func (c *httpClient) logRequest(req *http.Request, method, url string, bodyBuffer *bytes.Buffer) { +func (c *Client) logRequest(req *http.Request, method, url string, bodyBuffer *bytes.Buffer) { var reqBody string if bodyBuffer != nil { reqBody = bodyBuffer.String() @@ -292,20 +330,33 @@ func (c *httpClient) logRequest(req *http.Request, method, url string, bodyBuffe reqBody = "nil" } + reqLog := &RequestLog{ + Method: method, + URL: url, + Headers: req.Header, + Body: reqBody, + } + + e := c.requestLog(reqLog) + if e != nil { + if c.debug && c.logger != nil { + c.logger.Errorf("failed to log request: %v", e) + } + } + var logBuf bytes.Buffer err := reqLogTemplate.Execute(&logBuf, map[string]interface{}{ - "Method": method, - "URL": url, - "Headers": req.Header, - "Body": reqBody, + "Method": reqLog.Method, + "URL": reqLog.URL, + "Headers": reqLog.Headers, + "Body": reqLog.Body, }) if err == nil { c.logger.Debugf(logBuf.String()) } } -// nolint:unused -func (c *httpClient) sendRequest(req *http.Request) (*http.Response, error) { +func (c *Client) sendRequest(req *http.Request) (*http.Response, error) { resp, err := c.httpClient.Do(req) if err != nil { if c.debug && c.logger != nil { @@ -316,9 +367,8 @@ func (c *httpClient) sendRequest(req *http.Request) (*http.Response, error) { return resp, nil } -// nolint:unused -func (c *httpClient) checkHTTPError(resp *http.Response) error { - _, err := coupleAPIErrorsHTTP(resp, nil) +func (c *Client) checkHTTPError(resp *http.Response) error { + _, err := coupleAPIErrors(resp, nil) if err != nil { if c.debug && c.logger != nil { c.logger.Errorf("received HTTP error: %v", err) @@ -328,8 +378,7 @@ func (c *httpClient) checkHTTPError(resp *http.Response) error { return nil } -// nolint:unused -func (c *httpClient) logResponse(resp *http.Response) (*http.Response, error) { +func (c *Client) logResponse(resp *http.Response) (*http.Response, error) { var respBody bytes.Buffer if _, err := io.Copy(&respBody, resp.Body); err != nil { c.logger.Errorf("failed to read response body: %v", err) @@ -349,8 +398,7 @@ func (c *httpClient) logResponse(resp *http.Response) (*http.Response, error) { return resp, nil } -// nolint:unused -func (c *httpClient) decodeResponseBody(resp *http.Response, response interface{}) error { +func (c *Client) decodeResponseBody(resp *http.Response, response interface{}) error { if err := json.NewDecoder(resp.Body).Decode(response); err != nil { if c.debug && c.logger != nil { c.logger.Errorf("failed to decode response: %v", err) @@ -360,71 +408,24 @@ func (c *httpClient) decodeResponseBody(resp *http.Response, response interface{ return nil } -// R wraps resty's R method -func (c *Client) R(ctx context.Context) *resty.Request { - return c.resty.R(). - ExpectContentType("application/json"). - SetHeader("Content-Type", "application/json"). - SetContext(ctx). - SetError(APIError{}) -} - -// SetDebug sets the debug on resty's client func (c *Client) SetDebug(debug bool) *Client { c.debug = debug - c.resty.SetDebug(debug) return c } -// SetLogger allows the user to override the output -// logger for debug logs. func (c *Client) SetLogger(logger Logger) *Client { - c.resty.SetLogger(logger) - - return c -} - -//nolint:unused -func (c *httpClient) httpSetDebug(debug bool) *httpClient { - c.debug = debug - - return c -} - -//nolint:unused -func (c *httpClient) httpSetLogger(logger httpLogger) *httpClient { c.logger = logger return c } -// OnBeforeRequest adds a handler to the request body to run before the request is sent -func (c *Client) OnBeforeRequest(m func(request *Request) error) { - c.resty.OnBeforeRequest(func(_ *resty.Client, req *resty.Request) error { - return m(req) - }) -} - -// OnAfterResponse adds a handler to the request body to run before the request is sent -func (c *Client) OnAfterResponse(m func(response *Response) error) { - c.resty.OnAfterResponse(func(_ *resty.Client, req *resty.Response) error { - return m(req) - }) -} - -// nolint:unused -func (c *httpClient) httpOnBeforeRequest(m func(*http.Request) error) *httpClient { +func (c *Client) OnBeforeRequest(m func(*http.Request) error) { c.onBeforeRequest = append(c.onBeforeRequest, m) - - return c } -// nolint:unused -func (c *httpClient) httpOnAfterResponse(m func(*http.Response) error) *httpClient { +func (c *Client) OnAfterResponse(m func(*http.Response) error) { c.onAfterResponse = append(c.onAfterResponse, m) - - return c } // UseURL parses the individual components of the given API URL and configures the client @@ -458,7 +459,6 @@ func (c *Client) UseURL(apiURL string) (*Client, error) { return c, nil } -// SetBaseURL sets the base URL of the Linode v4 API (https://api.linode.com/v4) func (c *Client) SetBaseURL(baseURL string) *Client { baseURLPath, _ := url.Parse(baseURL) @@ -496,51 +496,68 @@ func (c *Client) updateHostURL() { apiProto = c.apiProto } - c.resty.SetBaseURL( - fmt.Sprintf( - "%s://%s/%s", - apiProto, - baseURL, - url.PathEscape(apiVersion), - ), - ) + c.hostURL = strings.TrimRight(fmt.Sprintf("%s://%s/%s", apiProto, baseURL, url.PathEscape(apiVersion)), "/") +} + +func (c *Client) Transport() (*http.Transport, error) { + if transport, ok := c.httpClient.Transport.(*http.Transport); ok { + return transport, nil + } + return nil, fmt.Errorf("current transport is not an *http.Transport instance") +} + +func (c *Client) tlsConfig() (*tls.Config, error) { + transport, err := c.Transport() + if err != nil { + return nil, err + } + if transport.TLSClientConfig == nil { + transport.TLSClientConfig = &tls.Config{ + MinVersion: tls.VersionTLS12, + } + } + return transport.TLSClientConfig, nil } // SetRootCertificate adds a root certificate to the underlying TLS client config func (c *Client) SetRootCertificate(path string) *Client { - c.resty.SetRootCertificate(path) + config, err := c.tlsConfig() + if err != nil { + c.logger.Errorf("%v", err) + return c + } + if config.RootCAs == nil { + config.RootCAs = x509.NewCertPool() + } + + config.RootCAs.AppendCertsFromPEM([]byte(path)) return c } // SetToken sets the API token for all requests from this client // Only necessary if you haven't already provided the http client to NewClient() configured with the token. func (c *Client) SetToken(token string) *Client { - c.resty.SetHeader("Authorization", fmt.Sprintf("Bearer %s", token)) + c.SetHeader("Authorization", fmt.Sprintf("Bearer %s", token)) return c } // SetRetries adds retry conditions for "Linode Busy." errors and 429s. func (c *Client) SetRetries() *Client { c. - addRetryConditional(linodeBusyRetryCondition). - addRetryConditional(tooManyRequestsRetryCondition). - addRetryConditional(serviceUnavailableRetryCondition). - addRetryConditional(requestTimeoutRetryCondition). - addRetryConditional(requestGOAWAYRetryCondition). - addRetryConditional(requestNGINXRetryCondition). + AddRetryCondition(LinodeBusyRetryCondition). + AddRetryCondition(TooManyRequestsRetryCondition). + AddRetryCondition(ServiceUnavailableRetryCondition). + AddRetryCondition(RequestTimeoutRetryCondition). + AddRetryCondition(RequestGOAWAYRetryCondition). + AddRetryCondition(RequestNGINXRetryCondition). SetRetryMaxWaitTime(APIRetryMaxWaitTime) - configureRetries(c) + ConfigureRetries(c) return c } // AddRetryCondition adds a RetryConditional function to the Client func (c *Client) AddRetryCondition(retryCondition RetryConditional) *Client { - c.resty.AddRetryCondition(resty.RetryConditionFunc(retryCondition)) - return c -} - -func (c *Client) addRetryConditional(retryConditional RetryConditional) *Client { - c.retryConditionals = append(c.retryConditionals, retryConditional) + c.retryConditionals = append(c.retryConditionals, retryCondition) return c } @@ -655,26 +672,26 @@ func (c *Client) UseCache(value bool) { // SetRetryMaxWaitTime sets the maximum delay before retrying a request. func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client { - c.resty.SetRetryMaxWaitTime(maxWaitTime) + c.retryMaxWaitTime = maxWaitTime return c } // SetRetryWaitTime sets the default (minimum) delay before retrying a request. func (c *Client) SetRetryWaitTime(minWaitTime time.Duration) *Client { - c.resty.SetRetryWaitTime(minWaitTime) + c.retryMinWaitTime = minWaitTime return c } // SetRetryAfter sets the callback function to be invoked with a failed request // to determine wben it should be retried. func (c *Client) SetRetryAfter(callback RetryAfter) *Client { - c.resty.SetRetryAfter(resty.RetryAfterFunc(callback)) + c.retryAfter = callback return c } // SetRetryCount sets the maximum retry attempts before aborting. func (c *Client) SetRetryCount(count int) *Client { - c.resty.SetRetryCount(count) + c.retryCount = count return c } @@ -695,13 +712,29 @@ func (c *Client) GetPollDelay() time.Duration { // client. // NOTE: Some headers may be overridden by the individual request functions. func (c *Client) SetHeader(name, value string) { - c.resty.SetHeader(name, value) + if c.header == nil { + c.header = make(http.Header) // Initialize header if nil + } + c.header.Set(name, value) +} + +func (c *Client) onRequestLog(rl func(*RequestLog) error) *Client { + if c.requestLog != nil { + c.logger.Warnf("Overwriting an existing on-request-log callback from=%s to=%s", + functionName(c.requestLog), functionName(rl)) + } + c.requestLog = rl + return c +} + +func functionName(i interface{}) string { + return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() } func (c *Client) enableLogSanitization() *Client { - c.resty.OnRequestLog(func(r *resty.RequestLog) error { + c.onRequestLog(func(r *RequestLog) error { // masking authorization header - r.Header.Set("Authorization", "Bearer *******************************") + r.Headers.Set("Authorization", "Bearer *******************************") return nil }) @@ -711,20 +744,25 @@ func (c *Client) enableLogSanitization() *Client { // NewClient factory to create new Client struct func NewClient(hc *http.Client) (client Client) { if hc != nil { - client.resty = resty.NewWithClient(hc) + client.httpClient = hc } else { - client.resty = resty.New() + client.httpClient = &http.Client{} + } + + // Ensure that the Header map is not nil + if client.httpClient.Transport == nil { + client.httpClient.Transport = &http.Transport{} } client.shouldCache = true client.cacheExpiration = APIDefaultCacheExpiration client.cachedEntries = make(map[string]clientCacheEntry) client.cachedEntryLock = &sync.RWMutex{} + client.configProfiles = make(map[string]ConfigProfile) client.SetUserAgent(DefaultUserAgent) baseURL, baseURLExists := os.LookupEnv(APIHostVar) - if baseURLExists { client.SetBaseURL(baseURL) } @@ -736,7 +774,6 @@ func NewClient(hc *http.Client) (client Client) { } certPath, certPathExists := os.LookupEnv(APIHostCert) - if certPathExists { cert, err := os.ReadFile(filepath.Clean(certPath)) if err != nil { diff --git a/client_http.go b/client_http.go deleted file mode 100644 index 7f16362c5..000000000 --- a/client_http.go +++ /dev/null @@ -1,56 +0,0 @@ -package linodego - -import ( - "net/http" - "sync" - "time" -) - -// Client is a wrapper around the Resty client -// -//nolint:unused -type httpClient struct { - //nolint:unused - httpClient *http.Client - //nolint:unused - userAgent string - //nolint:unused - debug bool - //nolint:unused - retryConditionals []httpRetryConditional - //nolint:unused - retryAfter httpRetryAfter - - //nolint:unused - pollInterval time.Duration - - //nolint:unused - baseURL string - //nolint:unused - apiVersion string - //nolint:unused - apiProto string - //nolint:unused - selectedProfile string - //nolint:unused - loadedProfile string - - //nolint:unused - configProfiles map[string]ConfigProfile - - // Fields for caching endpoint responses - //nolint:unused - shouldCache bool - //nolint:unused - cacheExpiration time.Duration - //nolint:unused - cachedEntries map[string]clientCacheEntry - //nolint:unused - cachedEntryLock *sync.RWMutex - //nolint:unused - logger httpLogger - //nolint:unused - onBeforeRequest []func(*http.Request) error - //nolint:unused - onAfterResponse []func(*http.Response) error -} diff --git a/client_test.go b/client_test.go index 93b133f97..d9f84ed6f 100644 --- a/client_test.go +++ b/client_test.go @@ -5,6 +5,8 @@ import ( "context" "errors" "fmt" + "github.com/jarcoal/httpmock" + "github.com/linode/linodego/internal/testutil" "net/http" "net/http/httptest" "reflect" @@ -12,8 +14,6 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "github.com/jarcoal/httpmock" - "github.com/linode/linodego/internal/testutil" ) func TestClient_SetAPIVersion(t *testing.T) { @@ -33,39 +33,39 @@ func TestClient_SetAPIVersion(t *testing.T) { client := NewClient(nil) - if client.resty.BaseURL != defaultURL { - t.Fatal(cmp.Diff(client.resty.BaseURL, defaultURL)) + if client.hostURL != defaultURL { + t.Fatal(cmp.Diff(client.hostURL, defaultURL)) } client.SetBaseURL(baseURL) client.SetAPIVersion(apiVersion) - if client.resty.BaseURL != expectedHost { - t.Fatal(cmp.Diff(client.resty.BaseURL, expectedHost)) + if client.hostURL != expectedHost { + t.Fatal(cmp.Diff(client.hostURL, expectedHost)) } // Ensure setting twice does not cause conflicts client.SetBaseURL(updatedBaseURL) client.SetAPIVersion(updatedAPIVersion) - if client.resty.BaseURL != updatedExpectedHost { - t.Fatal(cmp.Diff(client.resty.BaseURL, updatedExpectedHost)) + if client.hostURL != updatedExpectedHost { + t.Fatal(cmp.Diff(client.hostURL, updatedExpectedHost)) } // Revert client.SetBaseURL(baseURL) client.SetAPIVersion(apiVersion) - if client.resty.BaseURL != expectedHost { - t.Fatal(cmp.Diff(client.resty.BaseURL, expectedHost)) + if client.hostURL != expectedHost { + t.Fatal(cmp.Diff(client.hostURL, expectedHost)) } // Custom protocol client.SetBaseURL(protocolBaseURL) client.SetAPIVersion(protocolAPIVersion) - if client.resty.BaseURL != protocolExpectedHost { - t.Fatal(cmp.Diff(client.resty.BaseURL, expectedHost)) + if client.hostURL != protocolExpectedHost { + t.Fatal(cmp.Diff(client.hostURL, expectedHost)) } } @@ -107,7 +107,7 @@ func TestClient_NewFromEnvToken(t *testing.T) { t.Fatal(err) } - if client.resty.Header.Get("Authorization") != "Bearer blah" { + if client.header.Get("Authorization") != "Bearer blah" { t.Fatal("token not found in auth header: blah") } } @@ -171,12 +171,12 @@ func TestDebugLogSanitization(t *testing.T) { logger.L.SetOutput(&lgr) mockClient.SetDebug(true) - if !mockClient.resty.Debug { + if !mockClient.debug { t.Fatal("debug should be enabled") } mockClient.SetHeader("Authorization", fmt.Sprintf("Bearer %s", plainTextToken)) - if mockClient.resty.Header.Get("Authorization") != fmt.Sprintf("Bearer %s", plainTextToken) { + if mockClient.header.Get("Authorization") != fmt.Sprintf("Bearer %s", plainTextToken) { t.Fatal("token not found in auth header") } @@ -204,22 +204,25 @@ func TestDebugLogSanitization(t *testing.T) { func TestDoRequest_Success(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"message":"success"}`)) + if r.URL.Path == "/v4/foo/bar" { + w.WriteHeader(http.StatusOK) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"message":"success"}`)) + } else { + http.NotFound(w, r) + } } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() - client := &httpClient{ - httpClient: server.Client(), - } + client := NewClient(server.Client()) + client.SetBaseURL(server.URL) params := RequestParams{ Response: &map[string]string{}, } - err := client.doRequest(context.Background(), http.MethodGet, server.URL, params) + err := client.doRequest(context.Background(), http.MethodGet, "/foo/bar", params, nil) // Pass only the endpoint if err != nil { t.Fatal(cmp.Diff(nil, err)) } @@ -231,31 +234,28 @@ func TestDoRequest_Success(t *testing.T) { } } -func TestDoRequest_FailedEncodeBody(t *testing.T) { - client := &httpClient{ - httpClient: http.DefaultClient, - } +func TestDoRequest_FailedReadBody(t *testing.T) { + client := NewClient(nil) + // Create a request with an invalid body params := RequestParams{ Body: map[string]interface{}{ "invalid": func() {}, }, } - err := client.doRequest(context.Background(), http.MethodPost, "http://example.com", params) - expectedErr := "failed to encode body" + err := client.doRequest(context.Background(), http.MethodPost, "/foo/bar", params, nil) + expectedErr := "failed to read body: params.Body is not an io.Reader" if err == nil || !strings.Contains(err.Error(), expectedErr) { t.Fatalf("expected error %q, got: %v", expectedErr, err) } } func TestDoRequest_FailedCreateRequest(t *testing.T) { - client := &httpClient{ - httpClient: http.DefaultClient, - } + client := NewClient(nil) - // Create a request with an invalid URL to simulate a request creation failure - err := client.doRequest(context.Background(), http.MethodGet, "http://invalid url", RequestParams{}) + // Create a request with an invalid method to simulate a request creation failure + err := client.doRequest(context.Background(), "bad method", "/foo/bar", RequestParams{}, nil) expectedErr := "failed to create request" if err == nil || !strings.Contains(err.Error(), expectedErr) { t.Fatalf("expected error %q, got: %v", expectedErr, err) @@ -264,26 +264,28 @@ func TestDoRequest_FailedCreateRequest(t *testing.T) { func TestDoRequest_Non2xxStatusCode(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "error", http.StatusInternalServerError) + http.Error(w, "error", http.StatusInternalServerError) // Simulate a 500 Internal Server Error } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() - client := &httpClient{ - httpClient: server.Client(), - } + client := NewClient(server.Client()) + client.SetBaseURL(server.URL) - err := client.doRequest(context.Background(), http.MethodGet, server.URL, RequestParams{}) + err := client.doRequest(context.Background(), http.MethodGet, "/foo/bar", RequestParams{}, nil) if err == nil { t.Fatal("expected error, got nil") } + httpError, ok := err.(Error) if !ok { t.Fatalf("expected error to be of type Error, got %T", err) } + if httpError.Code != http.StatusInternalServerError { t.Fatalf("expected status code %d, got %d", http.StatusInternalServerError, httpError.Code) } + if !strings.Contains(httpError.Message, "error") { t.Fatalf("expected error message to contain %q, got %v", "error", httpError.Message) } @@ -293,21 +295,21 @@ func TestDoRequest_FailedDecodeResponse(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`invalid json`)) + _, _ = w.Write([]byte(`invalid json`)) // Simulate invalid JSON } server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() - client := &httpClient{ - httpClient: server.Client(), - } + client := NewClient(server.Client()) + client.SetBaseURL(server.URL) params := RequestParams{ Response: &map[string]string{}, } - err := client.doRequest(context.Background(), http.MethodGet, server.URL, params) + err := client.doRequest(context.Background(), http.MethodGet, "/foo/bar", params, nil) expectedErr := "failed to decode response" + if err == nil || !strings.Contains(err.Error(), expectedErr) { t.Fatalf("expected error %q, got: %v", expectedErr, err) } @@ -325,24 +327,21 @@ func TestDoRequest_BeforeRequestSuccess(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() - client := &httpClient{ - httpClient: server.Client(), - } + client := NewClient(server.Client()) + client.SetBaseURL(server.URL) - // Define a mutator that successfully modifies the request mutator := func(req *http.Request) error { req.Header.Set("X-Custom-Header", "CustomValue") return nil } - client.httpOnBeforeRequest(mutator) + client.OnBeforeRequest(mutator) - err := client.doRequest(context.Background(), http.MethodGet, server.URL, RequestParams{}) + err := client.doRequest(context.Background(), http.MethodGet, "/foo/bar", RequestParams{}, nil) if err != nil { t.Fatalf("expected no error, got: %v", err) } - // Check if the header was successfully added to the captured request if reqHeader := capturedRequest.Header.Get("X-Custom-Header"); reqHeader != "CustomValue" { t.Fatalf("expected X-Custom-Header to be set to CustomValue, got: %v", reqHeader) } @@ -357,18 +356,18 @@ func TestDoRequest_BeforeRequestError(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() - client := &httpClient{ - httpClient: server.Client(), - } + client := NewClient(server.Client()) + client.SetBaseURL(server.URL) mutator := func(req *http.Request) error { return errors.New("mutator error") } - client.httpOnBeforeRequest(mutator) + client.OnBeforeRequest(mutator) - err := client.doRequest(context.Background(), http.MethodGet, server.URL, RequestParams{}) + err := client.doRequest(context.Background(), http.MethodGet, "/foo/bar", RequestParams{}, nil) expectedErr := "failed to mutate before request" + if err == nil || !strings.Contains(err.Error(), expectedErr) { t.Fatalf("expected error %q, got: %v", expectedErr, err) } @@ -387,23 +386,21 @@ func TestDoRequest_AfterResponseSuccess(t *testing.T) { tr := &testRoundTripper{ Transport: server.Client().Transport, } - client := &httpClient{ - httpClient: &http.Client{Transport: tr}, - } + client := NewClient(&http.Client{Transport: tr}) + client.SetBaseURL(server.URL) mutator := func(resp *http.Response) error { resp.Header.Set("X-Modified-Header", "ModifiedValue") return nil } - client.httpOnAfterResponse(mutator) + client.OnAfterResponse(mutator) - err := client.doRequest(context.Background(), http.MethodGet, server.URL, RequestParams{}) + err := client.doRequest(context.Background(), http.MethodGet, "/foo/bar", RequestParams{}, nil) if err != nil { t.Fatalf("expected no error, got: %v", err) } - // Check if the header was successfully added to the response if respHeader := tr.Response.Header.Get("X-Modified-Header"); respHeader != "ModifiedValue" { t.Fatalf("expected X-Modified-Header to be set to ModifiedValue, got: %v", respHeader) } @@ -418,17 +415,16 @@ func TestDoRequest_AfterResponseError(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(handler)) defer server.Close() - client := &httpClient{ - httpClient: server.Client(), - } + client := NewClient(server.Client()) + client.SetBaseURL(server.URL) mutator := func(resp *http.Response) error { return errors.New("mutator error") } - client.httpOnAfterResponse(mutator) + client.OnAfterResponse(mutator) - err := client.doRequest(context.Background(), http.MethodGet, server.URL, RequestParams{}) + err := client.doRequest(context.Background(), http.MethodGet, "/foo/bar", RequestParams{}, nil) expectedErr := "failed to mutate after response" if err == nil || !strings.Contains(err.Error(), expectedErr) { t.Fatalf("expected error %q, got: %v", expectedErr, err) @@ -440,11 +436,9 @@ func TestDoRequestLogging_Success(t *testing.T) { logger := createLogger() logger.l.SetOutput(&logBuffer) // Redirect log output to buffer - client := &httpClient{ - httpClient: http.DefaultClient, - debug: true, - logger: logger, - } + client := NewClient(nil) + client.SetDebug(true) + client.SetLogger(logger) handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) @@ -452,13 +446,14 @@ func TestDoRequestLogging_Success(t *testing.T) { _, _ = w.Write([]byte(`{"message":"success"}`)) } server := httptest.NewServer(http.HandlerFunc(handler)) + client.SetBaseURL(server.URL) defer server.Close() params := RequestParams{ Response: &map[string]string{}, } - err := client.doRequest(context.Background(), http.MethodGet, server.URL, params) + err := client.doRequest(context.Background(), http.MethodGet, server.URL, params, nil) if err != nil { t.Fatal(cmp.Diff(nil, err)) } @@ -467,8 +462,8 @@ func TestDoRequestLogging_Success(t *testing.T) { logInfoWithoutTimestamps := removeTimestamps(logInfo) // Expected logs with templates filled in - expectedRequestLog := "DEBUG RESTY Sending request:\nMethod: GET\nURL: " + server.URL + "\nHeaders: map[Accept:[application/json] Content-Type:[application/json]]\nBody: " - expectedResponseLog := "DEBUG RESTY Received response:\nStatus: 200 OK\nHeaders: map[Content-Length:[21] Content-Type:[text/plain; charset=utf-8]]\nBody: {\"message\":\"success\"}" + expectedRequestLog := "DEBUG Sending request:\nMethod: GET\nURL: " + server.URL + "\nHeaders: map[Accept:[application/json] Authorization:[Bearer *******************************] Content-Type:[application/json] User-Agent:[linodego/dev https://github.com/linode/linodego]]\nBody: " + expectedResponseLog := "DEBUG Received response:\nStatus: 200 OK\nHeaders: map[Content-Length:[21] Content-Type:[text/plain; charset=utf-8]]\nBody: {\"message\":\"success\"}" if !strings.Contains(logInfo, expectedRequestLog) { t.Fatalf("expected log %q not found in logs", expectedRequestLog) @@ -483,11 +478,9 @@ func TestDoRequestLogging_Error(t *testing.T) { logger := createLogger() logger.l.SetOutput(&logBuffer) // Redirect log output to buffer - client := &httpClient{ - httpClient: http.DefaultClient, - debug: true, - logger: logger, - } + client := NewClient(nil) + client.SetDebug(true) + client.SetLogger(logger) params := RequestParams{ Body: map[string]interface{}{ @@ -495,14 +488,14 @@ func TestDoRequestLogging_Error(t *testing.T) { }, } - err := client.doRequest(context.Background(), http.MethodPost, "http://example.com", params) - expectedErr := "failed to encode body" + err := client.doRequest(context.Background(), http.MethodPost, "/foo/bar", params, nil) + expectedErr := "failed to read body: params.Body is not an io.Reader" if err == nil || !strings.Contains(err.Error(), expectedErr) { t.Fatalf("expected error %q, got: %v", expectedErr, err) } logInfo := logBuffer.String() - expectedLog := "ERROR RESTY failed to encode body" + expectedLog := "ERROR failed to read body: params.Body is not an io.Reader" if !strings.Contains(logInfo, expectedLog) { t.Fatalf("expected log %q not found in logs", expectedLog) diff --git a/config_test.go b/config_test.go index b4b3db418..628cc1415 100644 --- a/config_test.go +++ b/config_test.go @@ -42,11 +42,11 @@ func TestConfig_LoadWithDefaults(t *testing.T) { expectedURL := "https://api.cool.linode.com/v4beta" - if client.resty.BaseURL != expectedURL { - t.Fatalf("mismatched host url: %s != %s", client.resty.BaseURL, expectedURL) + if client.hostURL != expectedURL { + t.Fatalf("mismatched host url: %s != %s", client.hostURL, expectedURL) } - if client.resty.Header.Get("Authorization") != "Bearer "+p.APIToken { + if client.header.Get("Authorization") != "Bearer "+p.APIToken { t.Fatalf("token not found in auth header: %s", p.APIToken) } } @@ -88,11 +88,11 @@ func TestConfig_OverrideDefaults(t *testing.T) { expectedURL := "https://api.cool.linode.com/v4" - if client.resty.BaseURL != expectedURL { - t.Fatalf("mismatched host url: %s != %s", client.resty.BaseURL, expectedURL) + if client.hostURL != expectedURL { + t.Fatalf("mismatched host url: %s != %s", client.hostURL, expectedURL) } - if client.resty.Header.Get("Authorization") != "Bearer "+p.APIToken { + if client.header.Get("Authorization") != "Bearer "+p.APIToken { t.Fatalf("token not found in auth header: %s", p.APIToken) } } @@ -124,7 +124,7 @@ func TestConfig_NoDefaults(t *testing.T) { t.Fatalf("mismatched api token: %s != %s", p.APIToken, "mytoken") } - if client.resty.Header.Get("Authorization") != "Bearer "+p.APIToken { + if client.header.Get("Authorization") != "Bearer "+p.APIToken { t.Fatalf("token not found in auth header: %s", p.APIToken) } } diff --git a/errors.go b/errors.go index be15c0146..566dddb60 100644 --- a/errors.go +++ b/errors.go @@ -1,6 +1,7 @@ package linodego import ( + "bytes" "encoding/json" "errors" "fmt" @@ -53,69 +54,43 @@ func (r APIErrorReason) String() string { return fmt.Sprintf("[%s] %s", r.Field, r.Reason) } -func coupleAPIErrors(r *resty.Response, err error) (*resty.Response, error) { +//nolint:nestif +func coupleAPIErrors(resp *http.Response, err error) (*http.Response, error) { if err != nil { - // an error was raised in go code, no need to check the resty Response return nil, NewError(err) } - if r.Error() == nil { - // no error in the resty Response - return r, nil + if resp == nil { + return nil, NewError(fmt.Errorf("response is nil")) } - // handle the resty Response errors - - // Check that response is of the correct content-type before unmarshalling - expectedContentType := r.Request.Header.Get("Accept") - responseContentType := r.Header().Get("Content-Type") - - // If the upstream Linode API server being fronted fails to respond to the request, - // the http server will respond with a default "Bad Gateway" page with Content-Type - // "text/html". - if r.StatusCode() == http.StatusBadGateway && responseContentType == "text/html" { //nolint:goconst - return nil, Error{Code: http.StatusBadGateway, Message: http.StatusText(http.StatusBadGateway)} - } - - if responseContentType != expectedContentType { - msg := fmt.Sprintf( - "Unexpected Content-Type: Expected: %v, Received: %v\nResponse body: %s", - expectedContentType, - responseContentType, - string(r.Body()), - ) - - return nil, Error{Code: r.StatusCode(), Message: msg} - } - - apiError, ok := r.Error().(*APIError) - if !ok || (ok && len(apiError.Errors) == 0) { - return r, nil - } - - return nil, NewError(r) -} - -//nolint:unused -func coupleAPIErrorsHTTP(resp *http.Response, err error) (*http.Response, error) { - if err != nil { - // an error was raised in go code, no need to check the http.Response - return nil, NewError(err) - } - - if resp == nil || resp.StatusCode < 200 || resp.StatusCode >= 300 { + if resp.StatusCode < 200 || resp.StatusCode >= 300 { // Check that response is of the correct content-type before unmarshalling - expectedContentType := resp.Request.Header.Get("Accept") + expectedContentType := "" + if resp.Request != nil && resp.Request.Header != nil { + expectedContentType = resp.Request.Header.Get("Accept") + } + responseContentType := resp.Header.Get("Content-Type") // If the upstream server fails to respond to the request, - // the http server will respond with a default error page with Content-Type "text/html". - if resp.StatusCode == http.StatusBadGateway && responseContentType == "text/html" { //nolint:goconst + // the HTTP server will respond with a default error page with Content-Type "text/html". + if resp.StatusCode == http.StatusBadGateway && responseContentType == "text/html" { return nil, Error{Code: http.StatusBadGateway, Message: http.StatusText(http.StatusBadGateway)} } if responseContentType != expectedContentType { - bodyBytes, _ := io.ReadAll(resp.Body) + if resp.Body == nil { + return nil, NewError(fmt.Errorf("response body is nil")) + } + + bodyBytes, err := io.ReadAll(resp.Body) + if err != nil { + return nil, NewError(fmt.Errorf("failed to read response body: %w", err)) + } + + resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) + msg := fmt.Sprintf( "Unexpected Content-Type: Expected: %v, Received: %v\nResponse body: %s", expectedContentType, @@ -138,7 +113,6 @@ func coupleAPIErrorsHTTP(resp *http.Response, err error) (*http.Response, error) return nil, Error{Code: resp.StatusCode, Message: apiError.Errors[0].String()} } - // no error in the http.Response return resp, nil } diff --git a/errors_test.go b/errors_test.go index 68428fcd6..19ea51056 100644 --- a/errors_test.go +++ b/errors_test.go @@ -119,98 +119,6 @@ func TestCoupleAPIErrors(t *testing.T) { } }) - t.Run("resty 500 response error with reasons", func(t *testing.T) { - if _, err := coupleAPIErrors(restyError("testreason", "testfield"), nil); err.Error() != "[500] [testfield] testreason" { - t.Error("resty error should return with proper format [code] [field] reason") - } - }) - - t.Run("resty 500 response error without reasons", func(t *testing.T) { - if _, err := coupleAPIErrors(restyError("", ""), nil); err != nil { - t.Error("resty error with no reasons should return no error") - } - }) - - t.Run("resty response with nil error", func(t *testing.T) { - emptyErr := &resty.Response{ - RawResponse: &http.Response{ - StatusCode: 500, - }, - Request: &resty.Request{ - Error: nil, - }, - } - if _, err := coupleAPIErrors(emptyErr, nil); err != nil { - t.Error("resty error with no reasons should return no error") - } - }) - - t.Run("generic html error", func(t *testing.T) { - rawResponse := ` -