在去语言中实现md5计算方式的方法有哪些

  介绍

本篇文章给大家分享的是有关在去语言中实现md5计算方式的方法有哪些,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

<强>先看第一种,简单粗暴:

func  md5sum1 (file 字符串),string  {   ,数据,err :=, ioutil.ReadFile(文件)   ,if  err  !=, nil  {   ,return “;“   ,}      ,return  fmt.Sprintf (“% x",, md5.Sum(数据)   }

之所以说其粗暴,是因为ReadFile里面其实调用了一个readall,分配内存是最多的。

<强>基准来一发:

var  test_path =,“/路径//file"   func  BenchmarkMd5Sum1 (b  * testing.B), {   ,for 小姐::=,0;,小姐:& lt;, b.N;,我+ +,{   ,md5sum1 (test_path)   ,}   } go  test  -test.run=none  -test.bench=癪 BenchmarkMd5Sum1美元“-benchtime=10 s  -benchmem      BenchmarkMd5Sum1-4 , 300, 43704982, ns/op  19408224, B/op  14, alloc/op   通过   ok  tmp  17.446 s

先说明下,这个文件大小是19405028字节,和上面的19408224 B/op非常接近,因为readall确实是分配了文件大小的内存,代码为证:

<强> ReadFile源码

//,ReadFile  reads 从而file  named  by  filename 以及returns 从而内容。//,A  successful  call  returns  err ==, nil,, not  err ==, EOF只Because  ReadFile//,reads 从而,whole 文件,,it  does  not  treat  an  EOF 得到Read  as  an 错误//用be 报道。   func  ReadFile (filename 字符串),([]字节,,错误),{   ,f, err :=, os.Open(文件名)   ,if  err  !=, nil  {   ,return  nil,犯错   ,}   ,defer  f.Close ()   ,//变# 39;s  a  good  but  not  certain  bet  that  FileInfo  will  tell  us  exactly 请;much    ,//阅读,,so 还是# 39;s  try  it  but  be  prepared  for 从而answer 用be 错误的。   var  n  int64      ,if  fi, err :=, f.Stat ();, err ==, nil  {   ,//不要# 39;t  preallocate  a  huge 缓冲区,just 拷贝的案件。   ,if  size :=, fi.Size ();, size  & lt;, 1 e9  {   n =,大小   ,}   ,}   ,//As  initial  capacity  for  readAll,, use  n  +, a  little  extra 拷贝case  Size  is 零,//大敌;以及用avoid  another  allocation  after  Read  has  filled 从而缓冲区只,readAll   ,//call  will  read  into  its  allocated  internal  buffer 便宜只If 从而size    ,//错了,,我们# 39;ll  either  waste  some  space  off 从而最终获得趁机reallocate  as 需要,但是   ,//拷贝,overwhelmingly  common  case 我们# 39;ll  get  it  just 正确的。   ,   ,//readAll 第二个参数是即将创建的,buffer 大小   ,return  readAll (f, n + bytes.MinRead)   }      func  readAll (r  io.Reader, capacity  int64), (b []字节,err 错误),{   ,//这个,buffer 的大小就是,file  size  +, bytes.MinRead       ,buf :=, bytes.NewBuffer(使([]字节,,0,,容量))   ,//If 从而buffer 溢出,will  get  bytes.ErrTooLarge我方表示歉意。   ,//Return  that  as  an 错误只Any  other  panic 仍然存在。   ,defer  func (), {   ,e :=,恢复()   ,if  e ==, nil  {   ,返回   ,}   ,if  panicErr, ok :=, e。(错误);,ok ,,, panicErr ==, bytes.ErrTooLarge  {=,err  panicErr   ,}else  {   ,恐慌(e)   ,}   ,}()   _的不同之处是,err =, buf.ReadFrom(右)   ,return  buf.Bytes(),犯错   }

<强> io。复制

<强>再看第二种,

func  md5sum2 (file 字符串),string  {   ,f, err :=, os.Open(文件)   ,if  err  !=, nil  {   ,return “;“   ,}   ,defer  f.Close ()      ,h :=, md5.New ()      _的不同之处是,err =, io.Copy (h, f)   ,if  err  !=, nil  {   ,return “;“   ,}      ,return  fmt.Sprintf (“% x",, h.Sum (nil))   }

在去语言中实现md5计算方式的方法有哪些