Skip to content

Instantly share code, notes, and snippets.

@nesv
Created June 30, 2016 13:45
Show Gist options
  • Save nesv/06175c88bc37e56bc739d02b5fe284f5 to your computer and use it in GitHub Desktop.
Save nesv/06175c88bc37e56bc739d02b5fe284f5 to your computer and use it in GitHub Desktop.
Get input from command-line arguments, or fallback to STDIN
package main
import (
"bufio"
"flag"
"os"
"strings"
)
func main() {
flag.Parse()
input := GetInput(flag.Args(), os.Stdin)
// Iterate over each input value.
for input.Scan() {
arg := input.Text()
// ...do something with arg
}
if err := input.Err(); err != nil {
log.Fatalln(err)
}
}
func GetInput(args []string, fallback io.Reader) *bufio.Scanner {
if len(args) > 0 {
return bufio.NewScanner(strings.NewReader(strings.Join(args, "\n")))
}
return bufio.NewScanner(fallback)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment