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.

50 lines
882 B

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
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 WriteFile(fileName string, fileBytes []byte) (string, error) {
  11. var (
  12. nameSplit []string
  13. tempFile *os.File
  14. err error
  15. )
  16. // Used to get the file extension
  17. // This could be improved with a mime-type lookup
  18. nameSplit = strings.Split(fileName, ".")
  19. tempFile, err = ioutil.TempFile("./uploads", "upload-*."+nameSplit[len(nameSplit)-1])
  20. if err != nil {
  21. return "", err
  22. }
  23. defer tempFile.Close()
  24. _, err = tempFile.Write(fileBytes)
  25. return filepath.Base(tempFile.Name()), err
  26. }
  27. func DownloadFile(url string) (string, error) {
  28. var (
  29. resp *http.Response
  30. fileBytes []byte
  31. err error
  32. )
  33. resp, err = http.Get(url)
  34. if err != nil {
  35. return "", err
  36. }
  37. defer resp.Body.Close()
  38. fileBytes, err = io.ReadAll(resp.Body)
  39. return WriteFile(url, fileBytes)
  40. }