Created
June 10, 2011 21:47
-
-
Save kylelemons/1019843 to your computer and use it in GitHub Desktop.
command-line utility for SHA1 hashing - modified from Guillermo Estrada
This file contains 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
/* | |
Hash - Guillermo Estrada | |
(modified to demonstrate Go idioms by Kyle Lemons) | |
Simple utility to obtain the MD5 and/or SHA-1 | |
of a file from the command line. | |
2011 | |
*/ | |
package main | |
// Typically, imports are sorted in alphabetical order | |
import ( | |
"crypto/md5" | |
"crypto/sha1" | |
"flag" | |
"fmt" | |
"hash" | |
"io" | |
"os" | |
) | |
// Flags can be defined in multiple packages and don't need to be defined in your main() | |
var ( | |
useMD5 = flag.Bool("md5", false, "-md5 calculate md5 hash of file") | |
useSHA1 = flag.Bool("sha1", false, "-sha1 calculate sha1 hash of file") | |
) | |
func main() { | |
flag.Parse() | |
// Blocks of var/const work just as well inside a function call | |
var ( | |
writers []io.Writer | |
hashes []hash.Hash | |
names []string | |
) | |
// Closures can be used to collect common operations into a nice, clean function call | |
push := func(name string, h hash.Hash) { | |
writers = append(writers, h) // a Hash is a writer, so this is easy | |
hashes = append(hashes, h) | |
names = append(names, name) | |
} | |
// Now any number of hashes can be added here with very little code | |
if *useMD5 { | |
push("MD5", md5.New()) | |
} | |
if *useSHA1 { | |
push("SHA1", sha1.New()) | |
} | |
if len(names) == 0 { | |
flag.Usage() | |
os.Exit(1) | |
} | |
in, err := os.Open(flag.Arg(0)) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
// The variadic expansion of a slice is really convenient. | |
io.Copy(io.MultiWriter(writers...), in) | |
for i, name := range names { | |
fmt.Printf("%4s: %x\n", name, hashes[i].Sum()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment