-
Notifications
You must be signed in to change notification settings - Fork 3
/
bytes.go
52 lines (40 loc) · 763 Bytes
/
bytes.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
package util
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"os"
"path/filepath"
"github.com/pkg/errors"
)
type Byter interface {
Bytes() []byte
}
func NewByter(b []byte) Byter {
return bytes.NewBuffer(b)
}
func CopyBytes(b []byte) []byte {
n := make([]byte, len(b))
copy(n, b)
return b
}
func GenerateChecksum(i io.Reader) (string, error) {
sha := sha256.New()
if _, err := io.Copy(sha, i); err != nil {
return "", errors.Wrap(err, "failed to get checksum")
}
return fmt.Sprintf("%x", sha.Sum(nil)), nil
}
func GenerateFileChecksum(p string) (string, error) {
f, err := os.Open(filepath.Clean(p))
if err != nil {
return "", err
}
c, err := GenerateChecksum(f)
if err != nil {
return "", err
}
_ = f.Close()
return c, nil
}