passwords.go 643 B

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