How to Read from stdin in Go

Reading from stdin in go is as easy as reading from os.Stdin - the ioutil.ReadAll method reads all bytes into a buffer and allows you to handle the input once it is read. If you need to stream data to a go program you need to read os.Stdin in some buffered way - since ioutil.ReadAll blocks until it receives a EOF.

package main

import "os"
import "log"
import "io/ioutil"

func main() {
    bytes, err := ioutil.ReadAll(os.Stdin)

    log.Println(err, string(bytes))
}

This program will just print out all input it is handed through stdin (either piped, or redirected)

Related Posts