check.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package http
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "github.com/pkg/errors"
  7. )
  8. // An ErrorResponse reports errors caused by an API request.
  9. type ErrorResponse struct {
  10. Response *http.Response `json:",omitempty"`
  11. Body []byte
  12. }
  13. func (r *ErrorResponse) Error() string {
  14. return fmt.Sprintf("%v %v: %d\n%v",
  15. r.Response.Request.Method, r.Response.Request.URL,
  16. r.Response.StatusCode, string(r.Body))
  17. }
  18. // CheckResponse checks the API response for errors, and returns them if
  19. // present. A response is considered an error if it has a status code outside
  20. // the 200 range. API error responses are expected to have either no response
  21. // body, or a JSON response body that maps to ErrorResponse. Any other
  22. // response body will be silently ignored.
  23. func CheckResponse(r *http.Response) error {
  24. if c := r.StatusCode; 200 <= c && c <= 299 {
  25. return nil
  26. }
  27. errorResponse := &ErrorResponse{Response: r}
  28. var err error
  29. errorResponse.Body, err = ioutil.ReadAll(r.Body)
  30. if err != nil {
  31. return errors.Wrapf(err, "cryptix/http: ReadAll(resp.Body) failed. URL: %s", r.Request.URL.String())
  32. }
  33. return errorResponse
  34. }