Skip to content

Instantly share code, notes, and snippets.

@marekkowalczyk
Last active November 15, 2020 02:05
Show Gist options
  • Save marekkowalczyk/ee3e2f1a7b49c750dae82e308a57162f to your computer and use it in GitHub Desktop.
Save marekkowalczyk/ee3e2f1a7b49c750dae82e308a57162f to your computer and use it in GitHub Desktop.
Helper command: returns input from command line OR pipe --- but not both
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"time"
)
/*--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--*/
func main() {
if len(getArgs()) != 0 && len(getPipe()) != 0 {
log.Fatal("Both arguments and pipe used. Choose one.")
} // You cannot have both command-line and piped input
fmt.Print(getArgs())
fmt.Print(getPipe())
} // Empty input produces empty output
/*--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--*/
func getArgs() string { // Read command-line parameters
i := strings.Join(os.Args[1:], " ")
if len(i) == 0 {
return ""
}
return i
}
func getPipe() string { // Read piped input
input := make(chan string, 1)
go readInput(input)
select {
case <-time.After(5 * time.Millisecond): // Timeout length
return ""
case i := <-input:
return i
}
}
/*--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--/\/--*/
func readInput(input chan string) { // Helper function for getPipe()
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
pipe := scanner.Text()
input <- pipe
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment