-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #31 from etherlabsio:feat/add-client-response-chec…
…kers add; http client utility functions
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package httputil | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/etherlabsio/errors" | ||
) | ||
|
||
// CheckResponse checks the API response for errors, and returns them if | ||
// present. A response is considered an error if it has a status code outside | ||
// the 200 range or equal to 202 Accepted. | ||
// API error responses are expected to have either no response | ||
// body, or a JSON response body that maps to ErrorResponse. Any other | ||
// response body will be silently ignored. | ||
// | ||
// The error type will be *TwoFactorAuthError for two-factor authentication errors. | ||
func CheckResponse(r *http.Response) error { | ||
success := func(statusCode int) bool { | ||
return 200 <= statusCode && statusCode < 500 | ||
}(r.StatusCode) | ||
if success { | ||
return nil | ||
} | ||
return errors.New("internal server error with http status: "+r.Status, errors.Internal) | ||
} | ||
|
||
// CheckOKResponse checks if the status code is within 2XX range | ||
func CheckOKResponse(r *http.Response) error { | ||
isOK := r.StatusCode >= 200 && r.StatusCode <= 299 | ||
if !isOK { | ||
return errors.New("response error with http status: "+r.Status, errors.Internal) | ||
} | ||
return nil | ||
} |