Skip to content

Commit 44723d3

Browse files
Merge pull request #31 from etherlabsio:feat/add-client-response-checkers
add; http client utility functions
2 parents 6cc4e3c + 5e294ac commit 44723d3

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

httputil/client.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package httputil
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/etherlabsio/errors"
7+
)
8+
9+
// CheckResponse checks the API response for errors, and returns them if
10+
// present. A response is considered an error if it has a status code outside
11+
// the 200 range or equal to 202 Accepted.
12+
// API error responses are expected to have either no response
13+
// body, or a JSON response body that maps to ErrorResponse. Any other
14+
// response body will be silently ignored.
15+
//
16+
// The error type will be *TwoFactorAuthError for two-factor authentication errors.
17+
func CheckResponse(r *http.Response) error {
18+
success := func(statusCode int) bool {
19+
return 200 <= statusCode && statusCode < 500
20+
}(r.StatusCode)
21+
if success {
22+
return nil
23+
}
24+
return errors.New("internal server error with http status: "+r.Status, errors.Internal)
25+
}
26+
27+
// CheckOKResponse checks if the status code is within 2XX range
28+
func CheckOKResponse(r *http.Response) error {
29+
isOK := r.StatusCode >= 200 && r.StatusCode <= 299
30+
if !isOK {
31+
return errors.New("response error with http status: "+r.Status, errors.Internal)
32+
}
33+
return nil
34+
}

0 commit comments

Comments
 (0)