|
|
- package util
-
- import (
- "io"
- "io/ioutil"
- "net/http"
- "os"
- "path/filepath"
- "strings"
- )
-
- func WriteFile(fileName string, fileBytes []byte) (string, error) {
- var (
- nameSplit []string
- tempFile *os.File
- err error
- )
-
- // Used to get the file extension
- // This could be improved with a mime-type lookup
- nameSplit = strings.Split(fileName, ".")
-
- tempFile, err = ioutil.TempFile("./uploads", "upload-*."+nameSplit[len(nameSplit)-1])
- if err != nil {
- return "", err
- }
- defer tempFile.Close()
-
- _, err = tempFile.Write(fileBytes)
-
- return filepath.Base(tempFile.Name()), err
- }
-
- func DownloadFile(url string) (string, error) {
- var (
- resp *http.Response
- fileBytes []byte
- err error
- )
-
- resp, err = http.Get(url)
- if err != nil {
- return "", err
- }
- defer resp.Body.Close()
-
- fileBytes, err = io.ReadAll(resp.Body)
-
- return WriteFile(url, fileBytes)
- }
|