utils.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "os"
  7. "path"
  8. log "github.com/sirupsen/logrus"
  9. )
  10. type dataSource struct {
  11. SourceURL string `yaml:"source_url"`
  12. DestPath string `yaml:"dest_file"`
  13. }
  14. func downloadFile(url string, destPath string) error {
  15. log.Debugf("downloading %s in %s", url, destPath)
  16. req, err := http.NewRequest("GET", url, nil)
  17. if err != nil {
  18. return err
  19. }
  20. resp, err := http.DefaultClient.Do(req)
  21. if err != nil {
  22. return err
  23. }
  24. defer resp.Body.Close()
  25. body, err := ioutil.ReadAll(resp.Body)
  26. if err != nil {
  27. return err
  28. }
  29. if resp.StatusCode != 200 {
  30. return fmt.Errorf("download response 'HTTP %d' : %s", resp.StatusCode, string(body))
  31. }
  32. file, err := os.OpenFile(destPath, os.O_RDWR|os.O_CREATE, 0644)
  33. if err != nil {
  34. return err
  35. }
  36. _, err = file.WriteString(string(body))
  37. if err != nil {
  38. return err
  39. }
  40. err = file.Sync()
  41. if err != nil {
  42. return err
  43. }
  44. return nil
  45. }
  46. func getData(data []*dataSource, dataDir string) error {
  47. for _, dataS := range data {
  48. destPath := path.Join(dataDir, dataS.DestPath)
  49. log.Infof("downloading data '%s' in '%s'", dataS.SourceURL, destPath)
  50. err := downloadFile(dataS.SourceURL, destPath)
  51. if err != nil {
  52. return err
  53. }
  54. }
  55. return nil
  56. }