Skip to content

Instantly share code, notes, and snippets.

@magiconair
Last active December 16, 2015 15:39
Show Gist options
  • Save magiconair/5457674 to your computer and use it in GitHub Desktop.
Save magiconair/5457674 to your computer and use it in GitHub Desktop.
Simple reader/writer in Go
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func reader(path string, p chan string) {
f, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
defer f.Close()
buf := bufio.NewReader(f)
for {
line, err := buf.ReadString('\n')
if err != nil {
break
}
p <- line
}
}
func writer(p chan string) {
for line := range p {
fmt.Print(line)
}
}
func main() {
p := make(chan string)
go func() { reader(os.Args[1], p); close(p) }()
writer(p)
}
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func reader(path string, p chan string) {
f, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
defer f.Close()
buf := bufio.NewReader(f)
for {
line, err := buf.ReadString('\n')
if err != nil {
break
}
p <- line
}
}
func writer(p chan string) {
for line := range p {
fmt.Print(line)
}
}
func main() {
p := make(chan string, 10)
qr := make(chan int)
qw := make(chan int)
for i := 1; i < len(os.Args); i++ {
go func(i int) { reader(os.Args[i], p); qr <- 1 }(i)
}
go func() { writer(p); qw <- 1 }()
for i := 1; i < len(os.Args); i++ {
<-qr
}
close(p)
<-qw
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment