Ir al contenido principal

Go: Calculating the MD5 hash of a struct

In some scenarios, calculating the hash of a piece of data is useful, for instance when you only need to know that something in the dataset has changed, no matter what.

Calculating a hash is moderately computing consuming but has some advantadges:

  • Avoids checking the changes field by field of the dataset
  • Allows storing only the data hash instead of the whole dataset

In Golang, calculating MD5 hashes of structs can be achieved by using a code piece as this:

import (
  "bytes"
  "crypto/md5"
  "encoding/gob"
  "encoding/hex"
  "fmt"
)

// Random struct, just for demo purposes
type MySubStruct struct {
  Zaz *bool
}
type MyStruct struct {
  Foo int
  Bar []string
  Baz MySubStruct
}

func main() {
  // Hasheable struct
  myBool := false
  myStruct := MyStruct{
    Foo: 67372388,
    Bar: []string{"b", "ar", ""},
    Baz: MySubStruct{
      Zaz: &myBool,
    },
  }

  // Create a gob encoder 
  // and a buffer for storing the encoded struct
  var buffer bytes.Buffer
  encoder := gob.NewEncoder(&buffer)
  encoder.Encode(myStruct)

  // Calculate the MD5 hash of the buffered data
  md5Hash := md5.Sum(buffer.Bytes())
    
  // Print the hash as hex string
  hexedMD5Hash := hex.EncodeToString(md5Hash[:])
  fmt.Println(hexedMD5Hash)
}
  

You can try the above example in the Go playground

Comentarios