Skip to content

Instantly share code, notes, and snippets.

@miku
Forked from sgmac/pipeTee.go
Created December 29, 2016 00:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miku/d8be387909fc11d1b446c5b4a85da686 to your computer and use it in GitHub Desktop.
Save miku/d8be387909fc11d1b446c5b4a85da686 to your computer and use it in GitHub Desktop.
Example using io.TeeReader and io.Pipe
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"sync"
)
var wg sync.WaitGroup
func main() {
resp, err := http.Get("http://www.get-ip.me/")
if err != nil {
log.Fatal(err)
}
pr, pw := io.Pipe()
wg.Add(1)
go func() {
fmt.Println("Writing in pipe writer in goroutine")
ioutil.ReadAll(io.TeeReader(resp.Body, pw))
defer func() {
resp.Body.Close()
pw.Close()
wg.Done()
}()
}()
scanner := bufio.NewScanner(pr)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
defer pr.Close()
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment