download.go 1003 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package caldiff
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "go-common/library/log"
  11. )
  12. const (
  13. errFormat = "Func:[%s] - Step:[%s] - Error:[%v]"
  14. )
  15. // DownloadFile downloads one file from url to local
  16. func (d *Dao) DownloadFile(ctx context.Context, api string, fileName string) (bts int64, err error) {
  17. var (
  18. res []byte
  19. f *os.File
  20. req *http.Request
  21. )
  22. if req, err = d.client.NewRequest(http.MethodGet, api, "", url.Values{}); err != nil {
  23. log.Error(errFormat, "saveFile", fmt.Sprintf("httpGetURL-(%s)", api), err)
  24. return
  25. }
  26. if res, err = d.client.Raw(ctx, req); err != nil {
  27. log.Error(errFormat, "saveFile", fmt.Sprintf("httpGetURL-(%s)", api), err)
  28. return
  29. }
  30. if f, err = os.Create(fileName); err != nil {
  31. log.Error(errFormat, "saveFile", fmt.Sprintf("CreateFile(%s)", fileName), err)
  32. return
  33. }
  34. if bts, err = io.Copy(f, bytes.NewReader(res)); err != nil {
  35. log.Error(errFormat, "saveFile", fmt.Sprintf("SaveFile(%s)", fileName), err)
  36. }
  37. return
  38. }