Skip to content

Instantly share code, notes, and snippets.

@ashtonmeuser
Created April 13, 2021 06:15
Show Gist options
  • Save ashtonmeuser/1278a60145c9d6ec7b79e62def735ba2 to your computer and use it in GitHub Desktop.
Save ashtonmeuser/1278a60145c9d6ec7b79e62def735ba2 to your computer and use it in GitHub Desktop.
Calculate hash as an io.Reader is read
package hasher
import (
"crypto/sha1"
"encoding/hex"
"hash"
"io"
)
// HasherReader calculates the hash of a byte stream
// As an underlying io.Reader is read from, the hash is updated
type HasherReader struct {
hash hash.Hash
reader io.Reader
}
// NewHasherReader creates a new HasherReader from a provided io.Raeder
func NewHasherReader(r io.Reader) HasherReader {
hash := sha1.New()
reader := io.TeeReader(r, hash)
return HasherReader{hash, reader}
}
// Hash returns the hash value
// Ensure all contents of the underlying io.Reader have been read
func (h HasherReader) Hash() string {
return hex.EncodeToString(h.hash.Sum(nil))
}
// Read allows HasherReader to conform to io.Reader interface
func (h HasherReader) Read(p []byte) (n int, err error) {
return h.reader.Read(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment