speakeasy.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package speakeasy
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "strings"
  7. )
  8. // Ask the user to enter a password with input hidden. prompt is a string to
  9. // display before the user's input. Returns the provided password, or an error
  10. // if the command failed.
  11. func Ask(prompt string) (password string, err error) {
  12. return FAsk(os.Stdout, prompt)
  13. }
  14. // FAsk is the same as Ask, except it is possible to specify the file to write
  15. // the prompt to. If 'nil' is passed as the writer, no prompt will be written.
  16. func FAsk(wr io.Writer, prompt string) (password string, err error) {
  17. if wr != nil && prompt != "" {
  18. fmt.Fprint(wr, prompt) // Display the prompt.
  19. }
  20. password, err = getPassword()
  21. // Carriage return after the user input.
  22. if wr != nil {
  23. fmt.Fprintln(wr, "")
  24. }
  25. return
  26. }
  27. func readline() (value string, err error) {
  28. var valb []byte
  29. var n int
  30. b := make([]byte, 1)
  31. for {
  32. // read one byte at a time so we don't accidentally read extra bytes
  33. n, err = os.Stdin.Read(b)
  34. if err != nil && err != io.EOF {
  35. return "", err
  36. }
  37. if n == 0 || b[0] == '\n' {
  38. break
  39. }
  40. valb = append(valb, b[0])
  41. }
  42. return strings.TrimSuffix(string(valb), "\r"), nil
  43. }