Created
June 30, 2016 13:45
-
-
Save nesv/06175c88bc37e56bc739d02b5fe284f5 to your computer and use it in GitHub Desktop.
Get input from command-line arguments, or fallback to STDIN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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