Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reading data from stdin or a file in Go
/*
If no filename given as argument, read from stdin. Allows use as piped tool.
mashbridge@hex iotest$ go build iotest.go
mashbridge@hex iotest$ ./iotest x.txt
file data: foo bar
mashbridge@hex iotest$ ./iotest < x.txt
stdin data: foo bar
mashbridge@hex iotest$ echo "bingo" | ./iotest
stdin data: bingo
*/
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
flag.Parse()
var data []byte
var err error
switch flag.NArg() {
case 0:
data, err = ioutil.ReadAll(os.Stdin)
check(err)
fmt.Printf("stdin data: %v\n", string(data))
break
case 1:
data, err = ioutil.ReadFile(flag.Arg(0))
check(err)
fmt.Printf("file data: %v\n", string(data))
break
default:
fmt.Printf("input must be from stdin or file\n")
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.