Skip to content

Instantly share code, notes, and snippets.

@niski84
Created November 16, 2018 01:44
Show Gist options
  • Save niski84/85c284ea71defba072b7a23c177cff79 to your computer and use it in GitHub Desktop.
Save niski84/85c284ea71defba072b7a23c177cff79 to your computer and use it in GitHub Desktop.
golang download file
// Download File
func DownloadFile(url string, headers map[string]string, jsonData string, downloadFilePath string) (downloadedFile string, err error) {
var jsonStr = []byte(jsonData)
log.Printf("DownloadFile(): %v\n%+v...", url, jsonStr)
req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonStr))
for k,v := range(headers) {
log.Printf("setting header %v : %v ", k,v)
req.Header.Set(k, v)
}
// does support https?: yes
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
bodybytes, _ := ioutil.ReadAll(resp.Body)
body := string(bodybytes)
log.Printf("response:\n %+v ", body)
err = CheckResponse(resp, headers["sessionToken"], url, body, []string{}, err)
if err != nil {
return
}
// get filename
var filename string
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
if _, params, err := mime.ParseMediaType(cd); err == nil {
filename = params["filename"]
} else {
return "", err
}
}
downloadedFile = filepath.Join(downloadFilePath,filename)
out, err := os.Create(downloadedFile)
if err != nil {
return
}
defer out.Close()
bodyBuffer := bytes.NewBuffer(bodybytes)
io.Copy(out, bodyBuffer)
bodybytes, _ = ioutil.ReadAll(resp.Body)
body = string(bodybytes)
log.Printf("response:\n %+v ", body)
fi, err := os.Stat(downloadedFile);
size := fi.Size()
if err != nil || size == 0 {
return "", fmt.Errorf("Error downloading file. 0k or does not exist on disk: %+v \n ", downloadedFile)
}
return
}
// Check http response
func CheckResponse(resp *http.Response, sessionToken string, url string, body string, acceptedCodes []string, err error ) (error) {
if err != nil {
return err
}
// no errors; return
if resp.StatusCode == 200 {
return err
}
// session token expired
if resp.StatusCode == 401 {
return fmt.Errorf("session token (%v) is invalid or has expired", sessionToken)
}
log.Printf("accepted codes: %v", acceptedCodes)
// check if it's an accepted code for this call
if strings.Contains(strings.Join(acceptedCodes, ","), string(resp.StatusCode)) {
return err
} else {
return fmt.Errorf("Error: %v\n return status code is %v. response.body: %v", url, resp.StatusCode, body)
}
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment