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 struct tag and use field name to retrieve data?
+6.9k How to let Facebook Login button redirect to a particular URL ?
+5.7k Golang : Struct field tags and what is their purpose?
+5.8k Javascript : How to replace HTML inside <div>?
+10.6k Golang : Select region of interest with mouse click and crop from image
+9.6k Golang : Copy map(hash table) example
+9.4k Golang : Generate EAN barcode
+7.2k CloudFlare : Another way to get visitor's real IP address
+8.2k Golang : Routes multiplexer routing example with regular expression control
+19.6k Golang : Set or Add HTTP Request Headers
+48.5k Golang : Upload file from web browser to server
+6.1k Golang : Dealing with backquote