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
+22.9k Golang : Calculate time different
+14.6k Golang : Send email with attachment(RFC2822) using Gmail API example
+14.5k Golang : Overwrite previous output with count down timer
+10.5k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+36.7k Golang : Display float in 2 decimal points and rounding up or down
+5.8k Golang : Find change in a combination of coins example
+12.1k Golang : convert(cast) string to integer value
+7.5k Golang : How to handle file size larger than available memory panic issue
+4.7k JavaScript: Add marker function on Google Map
+11.9k Golang : Convert decimal number(integer) to IPv4 address
+9.5k Golang : Convert(cast) string to int64
+8.1k Golang : Multiplexer with net/http and map