From 565086cc2ad3a2ea1b76879ea5ade0f1cd8a901a Mon Sep 17 00:00:00 2001 From: ycdesu Date: Sat, 6 Feb 2021 09:16:43 +0800 Subject: [PATCH] util: extract IsError method --- pkg/exchange/max/maxapi/restapi.go | 8 +------- pkg/util/http_response.go | 4 ++++ pkg/util/http_response_test.go | 16 ++++++++++++++++ 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/pkg/exchange/max/maxapi/restapi.go b/pkg/exchange/max/maxapi/restapi.go index 1a0e9c3d4..000ba91bb 100644 --- a/pkg/exchange/max/maxapi/restapi.go +++ b/pkg/exchange/max/maxapi/restapi.go @@ -274,7 +274,7 @@ func (c *RestClient) sendRequest(req *http.Request) (*util.Response, error) { } // Check error, if there is an error, return the ErrorResponse struct type - if isError(response) { + if response.IsError() { errorResponse, err := toErrorResponse(response) if err != nil { return response, err @@ -359,12 +359,6 @@ func (r *ErrorResponse) Error() string { ) } -// isError check the response status code so see if a response is an error. -func isError(response *util.Response) bool { - var c = response.StatusCode - return c < 200 || c > 299 -} - // toErrorResponse tries to convert/parse the server response to the standard Error interface object func toErrorResponse(response *util.Response) (errorResponse *ErrorResponse, err error) { errorResponse = &ErrorResponse{Response: response} diff --git a/pkg/util/http_response.go b/pkg/util/http_response.go index 05698ec3c..7eef0346b 100644 --- a/pkg/util/http_response.go +++ b/pkg/util/http_response.go @@ -36,3 +36,7 @@ func (r *Response) String() string { func (r *Response) DecodeJSON(o interface{}) error { return json.Unmarshal(r.Body, o) } + +func (r *Response) IsError() bool { + return r.StatusCode >= 400 +} diff --git a/pkg/util/http_response_test.go b/pkg/util/http_response_test.go index 13fbe7897..d2b1a4c13 100644 --- a/pkg/util/http_response_test.go +++ b/pkg/util/http_response_test.go @@ -26,3 +26,19 @@ func TestResponse_DecodeJSON(t *testing.T) { assert.NoError(t, resp.DecodeJSON(&result)) assert.Equal(t, "Test Name", result.Name) } + +func TestResponse_IsError(t *testing.T) { + resp := &Response{Response: &http.Response{}} + cases := map[int]bool{ + 100: false, + 200: false, + 300: false, + 400: true, + 500: true, + } + + for code, isErr := range cases { + resp.StatusCode = code + assert.Equal(t, isErr, resp.IsError()) + } +}