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
+6.1k Golang : How to write backslash in string?
+9.6k Golang : Read file with ioutil
+8.3k Golang : Emulate NumPy way of creating matrix example
+6.6k Golang : Warp text string by number of characters or runes example
+4.7k MariaDB/MySQL : Form select statement or search query with Chinese characters
+13k Golang : Get terminal width and height example
+5.5k Golang : Display advertisement images or strings on random order
+30k Golang : Get time.Duration in year, month, week or day
+11.5k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+21.9k Golang : Use TLS version 1.2 and enforce server security configuration over client
+14.5k Golang : Overwrite previous output with count down timer
+9.4k Golang : Launch Mac OS X Preview (or other OS) application from your program example