Exemplo n.º 1
0
// checkHTTPStatus examines an HTTP response and returns an error if
// it is not successful.
func checkHTTPStatus(resp *http.Response) error {
	if len(resp.Status) > 0 && resp.Status[0] == '2' {
		return nil
	}

	// Always collect the entire body; we will need it as a fallback
	// and can only parse it once.
	var body []byte
	var err error
	if resp.Body != nil {
		body, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}
	}

	// Take a shot at decoding it as a better error
	var errResp restdata.ErrorResponse
	contentType := resp.Header.Get("Content-Type")
	err2 := restdata.Decode(contentType, bytes.NewReader(body), &errResp)
	if err2 == nil {
		// Given that we decoded that successfully, return the
		// server-provided error
		return errResp.ToError()
	}

	return ErrorHTTP{Response: resp, Body: string(body)}
}