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
+87.8k Golang : How to convert character to ASCII and back
+11.6k Swift : Convert (cast) Float to String
+9.1k Golang : Get curl -I or head data from URL example
+12.1k Golang : convert(cast) string to integer value
+13.9k Golang : How to check if a file is hidden?
+14k Golang : Human readable time elapsed format such as 5 days ago
+5.2k Golang : PGX CopyFrom to insert rows into Postgres database
+39k Golang : How to iterate over a []string(array)
+7.3k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+6k Golang : Experimenting with the Rejang script
+24.5k Golang : Change file read or write permission example
+10.4k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter