| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"os" |
| 7 |
|
| 8 |
"golang.org/x/term" |
| 9 |
) |
| 10 |
|
| 11 |
var ErrNoTerminal = errors.New("cannot read password from nonexistent terminal") |
| 12 |
|
| 13 |
type PasswordReader interface { |
| 14 |
ReadPassword() ([]byte, error) |
| 15 |
} |
| 16 |
|
| 17 |
type StdinPasswordReader struct{} |
| 18 |
|
| 19 |
func (pr StdinPasswordReader) ReadPassword() ([]byte, error) { |
| 20 |
if !term.IsTerminal(int(os.Stdin.Fd())) { |
| 21 |
return nil, ErrNoTerminal |
| 22 |
} |
| 23 |
|
| 24 |
password, err := term.ReadPassword(int(os.Stdin.Fd())) |
| 25 |
// Terminal echo is off while reading, so the user's Enter key does not |
| 26 |
// produce a visible newline. Emit one on stderr to match the prompt. |
| 27 |
fmt.Fprintln(os.Stderr) |
| 28 |
|
| 29 |
return password, err |
| 30 |
} |