-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
80 lines (64 loc) · 1.49 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package util
import (
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"os"
)
// CopyFile will copy the file to a other destination
func CopyFile(from, to string) error {
r, err := os.Open(from)
if err != nil {
return err
}
defer r.Close()
w, err := os.Create(to)
if err != nil {
return err
}
defer w.Close()
// do the actual work
_, err = io.Copy(w, r)
if err != nil {
return err
}
return err
}
// MoveFile will move the file to a other destination
func MoveFile(from, to string) error {
err := CopyFile(from, to)
err = os.Remove(from)
return err
}
// GetFileHash return a sha256 hashvalue of a file
func GetFileHash(filePath string) (string, error) {
f, err := os.Open(filePath)
if err != nil {
return "", err
}
defer f.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, f); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
// GetFileContentType give out the mimetype of a file
func GetFileContentType(filePath string) (string, error) {
f, err := os.Open(filePath)
if err != nil {
return "", err
}
defer f.Close()
// Only the first 512 bytes are used to sniff the content type.
buffer := make([]byte, 512)
_, err = f.Read(buffer)
if err != nil {
return "", err
}
// Use the net/http package's handy DectectContentType function. Always returns a valid
// content-type by returning "application/octet-stream" if no others seemed to match.
contentType := http.DetectContentType(buffer)
return contentType, nil
}