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
+8.6k Golang : Set or add headers for many or different handlers
+11.1k Golang : Read until certain character to break for loop
+13.7k Golang : Image to ASCII art example
+5.2k PHP : See installed compiled-in-modules
+18.8k Golang : Implement getters and setters
+21.8k Golang : How to reverse slice or array elements order
+20.9k PHP : Convert(cast) int to double/float
+8.6k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+11.6k Golang : Convert(cast) float to int
+14.4k Golang : Recombine chunked files example
+20.2k Golang : How to get struct tag and use field name to retrieve data?
+10.3k Golang : Wait and sync.WaitGroup example