Last active
December 19, 2015 11:09
-
-
Save RSully/5945292 to your computer and use it in GitHub Desktop.
My first Go program. Hash a file using a buffered reader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/** | |
* Help from: | |
* http://stackoverflow.com/questions/1821811/how-to-read-write-from-to-file | |
* https://groups.google.com/forum/#!topic/golang-nuts/1mc64pj_S50 | |
* http://pastebin.com/DgurHbpe | |
**/ | |
import ( | |
"io" | |
"bufio" | |
"os" | |
"flag" | |
"log" | |
"crypto/sha1" | |
"encoding/hex" | |
) | |
var file * string = flag.String("file", "", "File to hash") | |
func main() { | |
flag.Parse() | |
log.Println("Opening file: " + *file) | |
// Open a file handle and check for errors | |
fi, err := os.Open(*file) | |
if err != nil { | |
panic(err) | |
} | |
// Whenever we're done just close the file for us | |
defer func() { | |
// When we close the file check for errors too | |
err := fi.Close() | |
if err != nil { | |
panic(err) | |
} | |
}() | |
// Opened a buffered reader | |
r := bufio.NewReader(fi) | |
// Setup hasher | |
hasher := sha1.New() | |
// We're going to read the file in 4KB chunks | |
buf := make([]byte, 1024*4) | |
log.Println("Reading file ...") | |
for { | |
// log.Println("Reading data ...") | |
// Read the file, check for errors (except EOF) | |
n, err := r.Read(buf) | |
if err != nil && err != io.EOF { | |
panic(err) | |
} | |
// If there are 0 bytes left break from the loop | |
if n == 0 { | |
break | |
} | |
// Write to the hasher | |
_, err = hasher.Write(buf[:n]) | |
if err != nil { | |
panic(err) | |
} | |
} | |
// Output the sha | |
log.Println(hex.EncodeToString(hasher.Sum(nil))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment