Skip to content

Commit

Permalink
nil pointer panic, when no http response object
Browse files Browse the repository at this point in the history
  • Loading branch information
AskAlexSharov committed Jan 28, 2019
1 parent ea2d262 commit e7d3a65
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions loader/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,12 @@ func Image(ctx context.Context, filePathOrUrl string) Result {
var fileName string

if parsedUrl, ok := parseUrl(filePathOrUrl); ok {
resp, err := getByUrl(ctx, filePathOrUrl)
resp, closer, err := getByUrl(ctx, filePathOrUrl)
if err != nil {
return Result{Err: err}
}
defer func() {
if resp.Body != nil {
resp.Body.Close()
}
}()
defer closer()

img = resp.Body
fileName = parsedUrl.Path
} else { // then it's file
Expand Down Expand Up @@ -96,23 +93,28 @@ func decode(fileName string, f io.Reader) Result {
return result
}

func getByUrl(ctx context.Context, url string) (*http.Response, error) {
func getByUrl(ctx context.Context, url string) (*http.Response, func(), error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
return nil, nil, err
}

resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return nil, err
closer := func() {
if resp == nil || resp.Body == nil {
return
}

resp.Body.Close()
}

if err != nil {
return nil, closer, err
}
if resp.StatusCode != http.StatusOK {
if resp.Body != nil {
resp.Body.Close()
}
return nil, err
closer()
return nil, closer, err
}

return resp, nil
return resp, closer, nil
}

0 comments on commit e7d3a65

Please sign in to comment.