github.com/sandwich-go/boost@v1.3.29/xhash/md5/hash.go (about) 1 package md5 2 3 import ( 4 "crypto/md5" 5 "encoding/hex" 6 "io" 7 "os" 8 ) 9 10 // File 对文件进行 md5 hash 11 func File(filePath string) (string, error) { 12 //Open the passed argument and check for any error 13 file, err := os.Open(filePath) 14 if err != nil { 15 return "", err 16 } 17 //Tell the program to call the following function when the current function returns 18 defer func() { _ = file.Close() }() 19 return Buffer(file) 20 21 } 22 23 // Buffer 对数据流进行 md5 hash 24 func Buffer(src io.Reader) (string, error) { 25 var returnMD5String string 26 //Open a new hash interface to write to 27 hash := md5.New() 28 29 //Copy the file in the hash interface and check for any error 30 if _, err := io.Copy(hash, src); err != nil { 31 return returnMD5String, err 32 } 33 34 //Get the 16 bytes hash 35 hashInBytes := hash.Sum(nil)[:16] 36 37 //Convert the bytes to a string 38 return hex.EncodeToString(hashInBytes), nil 39 }