Skip to content

Instantly share code, notes, and snippets.

@nimezhu
Created October 23, 2016 03:35
Show Gist options
  • Save nimezhu/5d25e8c2adc91564c293703f8ba5aa60 to your computer and use it in GitHub Desktop.
Save nimezhu/5d25e8c2adc91564c293703f8ba5aa60 to your computer and use it in GitHub Desktop.
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