Last active
May 7, 2018 16:47
-
-
Save koral--/986cb9dbaeca55bc5474348798ba6f5b to your computer and use it in GitHub Desktop.
Defer statement in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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