You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
685 B

3 years ago
  1. package util
  2. import (
  3. "io"
  4. "io/ioutil"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. )
  10. func DownloadFile(url string) (string, error) {
  11. var (
  12. nameSplit []string
  13. resp *http.Response
  14. tempFile *os.File
  15. err error
  16. )
  17. // Used to get the file extension
  18. // This could be improved with a mime-type lookup
  19. nameSplit = strings.Split(url, ".")
  20. resp, err = http.Get(url)
  21. if err != nil {
  22. return "", err
  23. }
  24. defer resp.Body.Close()
  25. tempFile, err = ioutil.TempFile("./uploads", "upload-*."+nameSplit[len(nameSplit)-1])
  26. if err != nil {
  27. return "", err
  28. }
  29. defer tempFile.Close()
  30. _, err = io.Copy(tempFile, resp.Body)
  31. return filepath.Base(tempFile.Name()), err
  32. }