/* Want to write from os.Stdin to os.Stdout(fmt.Println() in below code) using channels*/
package main
import (
"fmt"
"io"
"os"
"bufio"
)
type message []byte
/* Function to run the groutine to run for stdin read */
func read (r io.Reader) <-chan message{
lines := make (chan message)
go func() {
defer close(lines)
scan := bufio.NewScanner(r)
for scan.Scan() {
lines <- message(scan.Bytes())
}
}()
return lines
}
func main() {
mes := make (chan message, 1)
sig := make (chan bool)
ch := read (os.Stdin) //Reading from Stdin
for {
select {
case anu := <-mes:
fmt.Println("Message to stdout")
fmt.Println(string(anu)) //Writing to Stdout
case mes <- <-ch:
fmt.Println("Message to channel 2")
continue
}
}
<-sig
/*
The O/P is :
go run writetochan.go
Golang
Message to channel 2
Fun <<< Delayed O/P golang means after putting one more
message only we are getting First message
Message to stdout
Golang
Expected O/P:
go run writetochan.go
Golang
Message to channel 2
Message to stdout
Golang
Fun
Message to channel 2
*/
}
Want to achieve the O/P shown above.
We are writing from one channel which reads all the stdin from the user and then writes to the stdout. Channel read is happening in goroutine. A dummy channel is formed (sig) so that we can run it indefinitely (Just for now).