1
0
Fork 0
mirror of https://github.com/imjasonh/go-marvel synced 2026-07-22 07:50:03 +00:00

refactor fetching

This commit is contained in:
Jason Hall 2014-04-25 22:51:41 -04:00
parent 4adae3bf24
commit 8dd60f8862

View file

@ -62,7 +62,7 @@ type commonList struct {
Count int `json:"count"` Count int `json:"count"`
} }
func (c Client) Series(id int64) (r struct { func (c Client) Series(id int64) (resp struct {
commonResponse commonResponse
Data struct { Data struct {
commonList commonList
@ -74,23 +74,26 @@ func (c Client) Series(id int64) (r struct {
}, err error) { }, err error) {
u := c.baseURL() u := c.baseURL()
u.Path += fmt.Sprintf("series/%d/comics", id) u.Path += fmt.Sprintf("series/%d/comics", id)
r, err := c.fetch(u)
resp, herr := http.Get(u.String()) if err != nil {
if herr != nil {
err = herr
return return
} }
defer resp.Body.Close() defer r.Close()
if resp.StatusCode >= http.StatusBadRequest { err = json.NewDecoder(r).Decode(&resp)
slurp, rerr := ioutil.ReadAll(resp.Body)
if rerr != nil {
err = rerr
return
}
err = fmt.Errorf("error response from API: %d\n%s", resp.StatusCode, slurp)
return
}
err = json.NewDecoder(resp.Body).Decode(&r)
return return
} }
func (c Client) fetch(u url.URL) (io.ReadCloser, error) {
resp, err := http.Get(u.String())
if err != nil {
return nil, err
}
if resp.StatusCode >= http.StatusBadRequest {
slurp, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("error response from API: %d\n%s", resp.StatusCode, slurp)
}
return resp.Body, nil
}