-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.go
54 lines (44 loc) · 1.06 KB
/
file.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
package main
import (
"bufio"
"fmt"
"io"
"net/http"
"os"
"path"
)
type File struct {
Name string
URL string
Extension string
}
// Create a directory folder based
// on the given name.
func CreateDir(name string) error {
path := path.Join(name)
return os.MkdirAll(path, os.ModePerm)
}
// Get a file from a URL.
func GetFile(URL string) (*http.Response, error) {
resp, err := http.Get(URL)
if err != nil {
return nil, err
}
return resp, nil
}
// Create a file based on the provided file struct,
// user information, and source reader, and save it into a folder.
func CreateFile(dir string, file File, source io.Reader) (*os.File, error) {
fullPath := path.Join(dir, file.Name+file.Extension)
createdFile, err := os.Create(fullPath)
if err != nil {
return nil, fmt.Errorf("error creating file: %s", err.Error())
}
bufferWriter := bufio.NewWriter(createdFile)
defer bufferWriter.Flush()
_, err = io.Copy(bufferWriter, source)
if err != nil {
return nil, fmt.Errorf("error copying from source: %s", err.Error())
}
return createdFile, nil
}