2020-02-19 20:26:47 +02:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"os"
|
2020-02-25 17:52:12 +02:00
|
|
|
"path/filepath"
|
2021-06-23 14:41:52 +02:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
|
|
|
"github.com/SAP/jenkins-library/pkg/piperutils"
|
2020-02-19 20:26:47 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
//Downloader ...
|
|
|
|
type Downloader interface {
|
|
|
|
SetOptions(options ClientOptions)
|
|
|
|
DownloadFile(url, filename string, header http.Header, cookies []*http.Cookie) error
|
|
|
|
}
|
|
|
|
|
|
|
|
// DownloadFile downloads a file's content as GET request from the specified URL to the specified file
|
|
|
|
func (c *Client) DownloadFile(url, filename string, header http.Header, cookies []*http.Cookie) error {
|
2020-02-20 13:46:32 +02:00
|
|
|
return c.DownloadRequest(http.MethodGet, url, filename, header, cookies)
|
2020-02-19 20:26:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// DownloadRequest ...
|
|
|
|
func (c *Client) DownloadRequest(method, url, filename string, header http.Header, cookies []*http.Cookie) error {
|
|
|
|
response, err := c.SendRequest(method, url, nil, header, cookies)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "HTTP %v request to %v failed with error", method, url)
|
|
|
|
}
|
|
|
|
defer response.Body.Close()
|
2020-02-25 17:52:12 +02:00
|
|
|
parent := filepath.Dir(filename)
|
|
|
|
if len(parent) > 0 {
|
|
|
|
if err = os.MkdirAll(parent, 0775); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-02-19 20:26:47 +02:00
|
|
|
fileHandler, err := os.Create(filename)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "unable to create file %v", filename)
|
|
|
|
}
|
|
|
|
defer fileHandler.Close()
|
|
|
|
|
2021-06-23 14:41:52 +02:00
|
|
|
_, err = piperutils.CopyData(fileHandler, response.Body)
|
2020-02-19 20:26:47 +02:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "unable to copy content from url to file %v", filename)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|