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
+19.2k Golang : How to Set or Add Header http.ResponseWriter?
+5.4k Unix/Linux/MacOSx : Get local IP address
+14.7k Golang : Save(pipe) HTTP response into a file
+6.4k Golang : Warp text string by number of characters or runes example
+27.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+6.9k Golang : Null and nil value
+6.5k How to let Facebook Login button redirect to a particular URL ?
+11k Golang : Post data with url.Values{}
+28.1k Golang : Read, Write(Create) and Delete Cookie example
+7.9k Golang : How To Use Panic and Recover
+10.2k Golang : Allow Cross-Origin Resource Sharing request
+29.4k Golang : Get time.Duration in year, month, week or day