-
Notifications
You must be signed in to change notification settings - Fork 41
/
sha1.go
75 lines (62 loc) · 1.18 KB
/
sha1.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
package main
import (
"compress/gzip"
"crypto/sha1"
"fmt"
"io"
"log"
"os"
"strings"
)
func main() {
/*
a := 1
{
// a := 2 // shadows outer a
a = 2 // change outer a
fmt.Println("inner", a) // affect only innter a
}
fmt.Println("outer", a)
return
*/
sig, err := sha1Sum("http.log.gz")
if err != nil {
log.Fatalf("error: %s", err)
}
fmt.Println(sig)
sig, err = sha1Sum("sha1.go")
if err != nil {
log.Fatalf("error: %s", err)
}
fmt.Println(sig)
}
/*
if file names ends with .gz
$ cat http.log.gz| gunzip | sha1sum
else
$ cat http.log.gz| sha1sum
*/
func sha1Sum(fileName string) (string, error) {
// idiom: acquire a resource, check for error, defer release
file, err := os.Open(fileName)
if err != nil {
return "", nil
}
defer file.Close() // deferred are called in LIFO order
var r io.Reader = file
if strings.HasSuffix(fileName, ".gz") {
gz, err := gzip.NewReader(file)
if err != nil {
return "", err
}
defer gz.Close()
r = gz
}
// io.CopyN(os.Stdout, r, 100)
w := sha1.New()
if _, err := io.Copy(w, r); err != nil {
return "", err
}
sig := w.Sum(nil)
return fmt.Sprintf("%x", sig), nil
}