diff --git a/response.go b/response.go index 4e13f44..f50bb80 100644 --- a/response.go +++ b/response.go @@ -30,31 +30,40 @@ type Output struct { } // PopulateFromHTTPResponse populates response based on HTTP response -func (r *Response) PopulateFromHTTPResponse(res *http.Response) { +func (r *Response) PopulateFromHTTPResponse(res *http.Response)(err error) { body, err := ioutil.ReadAll(res.Body) - check(err) + if err != nil { + return + } err = json.Unmarshal(body, &r) - - check(err) + if err != nil { + return + } // Get the output URL from the Location header r.URL = res.Header.Get("Location") + return } // SaveAs downloads and saves the compressed PNG file -func (r *Response) SaveAs(fn string) { +func (r *Response) SaveAs(fn string) (err error) { resp, err := http.Get(r.URL) - check(err) + if err != nil { + return + } defer resp.Body.Close() out, err := os.Create(fn) - check(err) + if err != nil { + return + } defer out.Close() - io.Copy(out, resp.Body) + _, err = io.Copy(out, resp.Body) + return } // Print a line of statistics diff --git a/tinypng.go b/tinypng.go index 392e18c..15ee998 100644 --- a/tinypng.go +++ b/tinypng.go @@ -24,13 +24,18 @@ func ShrinkFn(apiKey string, inputFilename string) (Response, error) { // Shrink allows you to shrink a PNG file using an open file handle. func Shrink(apiKey string, inputFile *os.File) (Response, error) { res, err := uploadPNG(apiKey, inputFile) - check(err) + if err != nil { + return Response{}, err + } defer res.Body.Close() var r Response - r.PopulateFromHTTPResponse(res) + err = r.PopulateFromHTTPResponse(res) + if err != nil { + return Response{}, err + } if res.StatusCode == 201 { return r, nil diff --git a/tinypng/main.go b/tinypng/main.go index 3ab1aec..6b096cd 100644 --- a/tinypng/main.go +++ b/tinypng/main.go @@ -75,7 +75,11 @@ func main() { } // Download the compressed PNG - res.SaveAs(outputFilename) + err = res.SaveAs(outputFilename) + if err != nil { + fatalError(err.Error()) + } + } // Handle input