Last active
July 16, 2017 09:11
-
-
Save shawnsmithdev/36ed42873a2062e400e8f7435d2db338 to your computer and use it in GitHub Desktop.
sha256 CLI tool
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
package main | |
import ( | |
"crypto/sha256" | |
"fmt" | |
"hash" | |
"io/ioutil" | |
"os" | |
) | |
// Gets the first cli argument as a string, or a empty string when no arguments are given | |
func getArg() (result string) { | |
result = "" | |
if len(os.Args) < 2 { | |
fmt.Println("Missing expected argument") | |
} else { | |
result = os.Args[1] | |
} | |
return result | |
} | |
type fileHasher interface { | |
hashFile(string) string | |
} | |
type sha256FileHasher struct { | |
hash.Hash | |
} | |
func (self *sha256FileHasher) hashFile(filePath string) (hash string) { | |
hash = "unknown" | |
data, err := ioutil.ReadFile(filePath) | |
if err != nil { | |
fmt.Printf("Cannot hash: %v\n", err) | |
return hash | |
} | |
self.Write(data) | |
hashBytes := self.Sum(nil) | |
self.Reset() | |
hash = fmt.Sprintf("%x", hashBytes) | |
return hash | |
} | |
func newSHA256FileHasher() (hasher fileHasher) { | |
return &sha256FileHasher{sha256.New()} | |
} | |
func main() { | |
filePath := getArg() | |
if filePath == "" { | |
return | |
} | |
hasher := newSHA256FileHasher() | |
hash := hasher.hashFile(filePath) | |
fmt.Printf("SHA256 hash of file at %v is %s\n", filePath, hash) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment