下面是GoLang 计算小文件或大文件 md5 值的例子
package main
import (
"crypto/md5"
"fmt"
"io"
"os"
)
func main() {
testFile := "/path/to/file"
file, err := os.Open(testFile)
if err != nil {
fmt.Println(err)
return
}
md5h := md5.New()
io.Copy(md5h, file)
fmt.Printf("%x", md5h.Sum([]byte(""))) //md5
}
如果是大文件,可以分块计算,参见下面例子:
package main
import (
"crypto/md5"
"fmt"
"io"
"math"
"os"
)
const filechunk = 8192 // we settle for 8KB
func main() {
file, err := os.Open("utf8.txt")
if err != nil {
panic(err.Error())