package main import ( "bufio" "fmt" "os" "golang.org/x/term" ) // readPassword prompts the user for a password on the given file // descriptor. If the fd is a terminal the input is hidden; otherwise // (piped stdin) it falls back to a plain read. func readPassword(prompt string) ([]byte, error) { fd := int(os.Stdin.Fd()) if term.IsTerminal(fd) { fmt.Fprint(os.Stderr, prompt) pw, err := term.ReadPassword(fd) fmt.Fprintln(os.Stderr) return pw, err } // Non-tty (piped): read a line without echo hiding. scanner := bufio.NewScanner(os.Stdin) if !scanner.Scan() { if err := scanner.Err(); err != nil { return nil, err } return nil, fmt.Errorf("no input on stdin") } return []byte(scanner.Text()), nil }