forked from levigross/grequests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_upload.go
61 lines (44 loc) · 1.6 KB
/
file_upload.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package grequests
import (
"errors"
"io"
"os"
"path/filepath"
)
// FileUpload is a struct that is used to specify the file that a User
// wishes to upload.
type FileUpload struct {
// Filename is the name of the file that you wish to upload. We use this to guess the mimetype as well as pass it onto the server
FileName string
// FileContents is happy as long as you pass it a io.ReadCloser (which most file use anyways)
FileContents io.ReadCloser
}
// FileUploadFromDisk allows you to create a FileUpload struct slice by just specifying a location on the disk
func FileUploadFromDisk(fileName string) ([]FileUpload, error) {
fd, err := os.Open(fileName)
if err != nil {
return nil, err
}
return []FileUpload{{FileContents: fd, FileName: fileName}}, nil
}
// FileUploadFromGlob allows you to create a FileUpload struct slice by just specifying a glob location on the disk
// this function will gloss over all errors in the files and only upload the files that don't return errors from the glob
func FileUploadFromGlob(fileSystemGlob string) ([]FileUpload, error) {
files, err := filepath.Glob(fileSystemGlob)
if err != nil {
return nil, err
}
if len(files) == 0 {
return nil, errors.New("grequests: No files have been returned in the glob")
}
filesToUpload := make([]FileUpload, 0, len(files))
for _, f := range files {
if s, err := os.Stat(f); err != nil || s.IsDir() {
continue
}
// ignoring error because I can stat the file
fd, _ := os.Open(f)
filesToUpload = append(filesToUpload, FileUpload{FileContents: fd, FileName: filepath.Base(fd.Name())})
}
return filesToUpload, nil
}