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
+9.9k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+12.1k Golang : Perform sanity checks on filename example
+5.4k Javascript : How to loop over and parse JSON data?
+44.9k Golang : Use wildcard patterns with filepath.Glob() example
+12.7k Golang : Pass database connection to function called from another package and HTTP Handler
+7.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+20.6k Nginx + FastCGI + Go Setup.
+13.9k Golang : convert(cast) string to float value
+9.4k Golang : Web(Javascript) to server-side websocket example
+17.3k Golang : How to tell if a file is compressed either gzip or zip ?
+7.5k Golang : Detect sample rate, channels or latency with PortAudio
+13.8k Golang : Gin framework accept query string by post request example