-
Notifications
You must be signed in to change notification settings - Fork 1
/
os.go
57 lines (47 loc) · 953 Bytes
/
os.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
package hash
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"hash"
"hash/crc32"
"io"
"os"
"github.com/spf13/cast"
)
type HashF struct {
Os *os.File
Close bool
}
func NewWithOs(o *os.File) *HashF {
return &HashF{Os: o, Close: true}
}
func (h *HashF) DisableAutoClose() *HashF {
h.Close = false
return h
}
func hashWithOs(fs *os.File, close bool, h hash.Hash) (string, error) {
_, _ = io.Copy(h, fs)
if close {
fs.Close()
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func (h *HashF) MD5() (string, error) {
return hashWithOs(h.Os, h.Close, md5.New())
}
func (h *HashF) SHA1() (string, error) {
return hashWithOs(h.Os, h.Close, sha1.New())
}
func (h *HashF) SHA256() (string, error) {
return hashWithOs(h.Os, h.Close, sha256.New())
}
func (h *HashF) CRC32() (string, error) {
hs := crc32.NewIEEE()
_, _ = io.Copy(hs, h.Os)
if h.Close {
h.Os.Close()
}
return cast.ToString(hs.Sum32()), nil
}