github.com/szyn/goreleaser@v0.76.1-0.20180517112710-333da09a1297/checksum/checksum.go (about)

     1  // Package checksum contain algorithms to checksum files
     2  package checksum
     3  
     4  import (
     5  	"crypto/sha256"
     6  	"encoding/hex"
     7  	"hash"
     8  	"io"
     9  	"os"
    10  )
    11  
    12  // SHA256 sum of the given file
    13  func SHA256(path string) (string, error) {
    14  	return calculate(sha256.New(), path)
    15  }
    16  
    17  func calculate(hash hash.Hash, path string) (string, error) {
    18  	file, err := os.Open(path)
    19  	if err != nil {
    20  		return "", err
    21  	}
    22  	defer file.Close() // nolint: errcheck
    23  
    24  	return doCalculate(hash, file)
    25  }
    26  
    27  func doCalculate(hash hash.Hash, file io.Reader) (string, error) {
    28  	_, err := io.Copy(hash, file)
    29  	if err != nil {
    30  		return "", err
    31  	}
    32  	return hex.EncodeToString(hash.Sum(nil)), nil
    33  }