I'm somewhat new to Go. A school assignment has me writing a wrapper in a language of our choice around various built-in hashing algorithms. I decided to use Go, and wrote up the following method (only including two of the algorithms for brevity):
package hash
import (
"crypto/md5"
"crypto/sha256"
"errors"
)
func Hash(data string, algorithm string) ([]byte, error) {
bytes := []byte(data)
switch algorithm {
case "md5":
hash := md5.Sum(bytes) // As far as I know, I need a temporary variable to convert to a slice.
return hash[:], nil
case "sha256":
hash := sha256.Sum256(bytes)
return hash[:], nil
default:
return []byte{}, errors.New("Unsupported Hash Algorithm: " + algorithm)
}
}
This method works and is sufficient for the assignment, but I'm wondering if it can be written better.
In particular, because the different hashing algorithms return variable-length arrays, I need to convert to slices, so the return hash[:], nil is repetitive. Additionally, almost all the real logic is in retrieving the specific method.
I tried to make a variable before the switch like var hash []byte but this still has the length problem.
I also tried to put all of the functions in a map where I would define pairs like hashes["md5"] := md5.Sum:
var (
hashes map[string]func([]byte) []byte
)
But this actually just makes creating the functions a mess, because I end up having to convert to a slice anyways.
hashes["md5"] := func(data []byte) []byte {
hash := md5.Sum(data)
return hash[:]
}
I recognize that the whole method is kind-of pointless since the need to make the wrapper is artificial, but it feels like my methodology is off and I'm somehow misunderstanding something about how arrays and slices are supposed to be treated in Go. Can I do better?