Skip to content

Instantly share code, notes, and snippets.

@koral--
Last active May 7, 2018 16:47
Show Gist options
  • Save koral--/986cb9dbaeca55bc5474348798ba6f5b to your computer and use it in GitHub Desktop.
Save koral--/986cb9dbaeca55bc5474348798ba6f5b to your computer and use it in GitHub Desktop.
Defer statement in Go
func downloadFile(downloadURL string, outFile *os.File) error {
response, err := http.Get(downloadURL)
if err != nil {
return err
}
defer func() {
if err := response.Body.Close(); err != nil {
log.Warnf("Failed to close (%s) body", downloadURL)
}
}()
if response.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download file from %s, error: %s", downloadURL, response.Status)
}
_, err = io.Copy(outFile, response.Body)
if err != nil {
return fmt.Errorf("failed to save file %s, error: %s", outFile.Name(), err)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment