How to write `cat` in Go using pipes

I have an implementation of the Unix cat tool below. It reads a few bytes from os.Stdin into the buffer, and then writes these bytes to os.Stdout . Is there a way in which I can skip the buffer and just connect Stdin to Stdout ?

 package main import "os" import "io" func main() { buf := make([]byte, 1024) var n int var err error for err != io.EOF { n, err = os.Stdin.Read(buf) if n > 0 { os.Stdout.Write(buf[0:n]) } } } 
+6
source share
2 answers

You can use io.Copy() (Documentation here)

Example:

 package main import ( "os" "io" "log" ) func main() { if _, err := io.Copy(os.Stdout, os.Stdin); err != nil { log.Fatal(err) } } 
+11
source

For instance,

 package main import ( "io" "os" ) func main() { io.Copy(os.Stdout, os.Stdin) } 
+5
source

Source: https://habr.com/ru/post/922067/


All Articles