Last active
April 15, 2019 16:13
-
-
Save BNPrashanth/8e41bc205c4723b964e2a57a95d295f2 to your computer and use it in GitHub Desktop.
This file contains 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 Download(url string, filename string, timeout int64) *u.ErrorResponse { | |
u.GeneralLogger.Println("Downloading", url, "...") | |
client := http.Client{ | |
Timeout: time.Duration(timeout * int64(time.Second)), | |
} | |
resp, err := client.Get(url) | |
if err != nil { | |
u.ErrorLogger.Println("Cannot download file from the given url", err) | |
return u.ReturnErrorResponse(err, "Cannot download file from the given url") | |
} | |
if resp.StatusCode != 200 { | |
u.ErrorLogger.Printf("Response from the URL was %d, but expecting 200", resp.StatusCode) | |
return u.ReturnErrorResponse( | |
errors.New("Response returned with a status different from 200"), | |
"Response returned with a status different from 200", | |
) | |
} | |
if resp.Header["Content-Type"][0] != "text/csv" { | |
u.ErrorLogger.Printf("The file downloaded has content type '%s', expected 'text/csv'.", resp.Header["Content-Type"]) | |
return u.ReturnErrorResponse( | |
errors.New("Downloaded file didn't contain the expected content-type: 'text/csv'"), | |
"Downloaded file didn't contain the expected content-type: 'text/csv'", | |
) | |
} | |
b, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
u.ErrorLogger.Println("Cannot read Body of Response", err) | |
return u.ReturnErrorResponse(err, "Cannot read Body of Response") | |
} | |
err = ioutil.WriteFile(filename, b, 0644) | |
if err != nil { | |
u.ErrorLogger.Println("Cannot write to file", err) | |
return u.ReturnErrorResponse(err, "Cannot write to file") | |
} | |
u.GeneralLogger.Println("Doc downloaded in ", filename) | |
return u.ReturnErrorResponse(nil, "") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment