-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathresponse_reader.go
More file actions
30 lines (25 loc) · 802 Bytes
/
response_reader.go
File metadata and controls
30 lines (25 loc) · 802 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package rclient
import (
"encoding/json"
"net/http"
)
// A ResponseReader attempts to read a *http.Response into v.
type ResponseReader func(resp *http.Response, v interface{}) error
// ReadJSONResponse attempts to marshal the response body into v
// if and only if the response StatusCode is in the 200 range.
// Otherwise, an error is thrown.
// It assumes the response body is in JSON format.
func ReadJSONResponse(resp *http.Response, v interface{}) error {
defer resp.Body.Close()
switch {
case resp.StatusCode < 200, resp.StatusCode > 299:
return NewResponseErrorf(resp, "Invalid status code: %d", resp.StatusCode)
case v == nil:
return nil
default:
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
return NewResponseError(resp, err.Error())
}
}
return nil
}