Golang io.TeeReader function example
package io
Golang io.TeeReader function usage example
package main
import (
"crypto/md5"
"fmt"
"io"
"os"
)
func main() {
// open files r and w
r, err := os.Open("input.txt")
if err != nil {
panic(err)
}
defer r.Close()
w, err := os.Create("output.txt")
if err != nil {
panic(err)
}
defer w.Close()
// we want to copy the file
// and at the same time create a MD5 checksum
hash := md5.New()
n, err := io.Copy(w, io.TeeReader(r, hash)) // <------ here !
if err != nil {
panic(err)
}
// the end result ?
// kill 2 birds with 1 stone thanks to io.TeeReader()
fmt.Printf("Copied %v bytes with checksum %x \n", n, hash.Sum(nil))
}
Sample output :
Copied 17 bytes with checksum 5af1ca1d92340d72a29c194d3f4096e0
References :
https://www.socketloop.com/tutorials/golang-generate-md5-checksum-of-a-file
Advertisement
Something interesting
Tutorials
+20.2k Golang : How to get own program name during runtime ?
+25k Golang : Create PDF file from HTML file
+9.3k Golang : How to get ECDSA curve and parameters data?
+33.6k Golang : How to check if slice or array is empty?
+9.9k Golang : Check if user agent is a robot or crawler example
+12.3k Golang : Validate email address
+8.3k Useful methods to access blocked websites
+29.2k Golang : missing Git command
+21.1k Golang : Convert(cast) string to rune and back to string example
+6.9k Golang : How to setup a disk space used monitoring service with Telegram bot
+6.5k Unix/Linux : How to get own IP address ?
+7.5k Golang : Gorrila set route name and get the current route name