Golang io.Pipe function example
package io
Golang io.Pipe function usage example
package main
import (
"compress/gzip"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"os"
)
func main() {
// read and write with pipe
pReader, pWriter := io.Pipe()
// use base64 encoder
b64Writer := base64.NewEncoder(base64.StdEncoding, pWriter)
gWriter := gzip.NewWriter(b64Writer)
// write text to be gzipped and push to pipe
go func() {
fmt.Println("Start writing")
n, err := gWriter.Write([]byte("These words will be compressed and push into pipe"))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
gWriter.Close()
b64Writer.Close()
pWriter.Close()
fmt.Printf("Written %d bytes \n", n)
}()
// start reading from the pipe(reverse of the above process)
// use base64 decoder to wrap pipe Reader
b64Reader := base64.NewDecoder(base64.StdEncoding, pReader)
// read gzipped text and decompressed the text
gReader, err := gzip.NewReader(b64Reader)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// print out the text
text, err := ioutil.ReadAll(gReader)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("%s\n", text)
}
Output :
Start writing
Written 49 bytes
These words will be compressed and push into pipe
References :
Advertisement
Something interesting
Tutorials
+12k Golang : Convert a rune to unicode style string \u
+7.3k Golang : How to fix html/template : "somefile" is undefined error?
+7.1k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+6.9k Golang : Decode XML data from RSS feed
+13.3k Golang : Date and Time formatting
+6.7k Golang : Check if password length meet the requirement
+17.6k Golang : Parse date string and convert to dd-mm-yyyy format
+14k Golang : concatenate(combine) strings
+17.4k Golang : Get future or past hours, minutes or seconds
+5.5k Golang : Stop goroutine without channel
+8.1k Golang : How To Use Panic and Recover
+12.1k Golang : Sort and reverse sort a slice of runes