speakeasy.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. // Same as the Ask function, except it is possible to specify the file to write
  15. // the prompt to.
  16. func FAsk(file *os.File, prompt string) (password string, err error) {
  17. if prompt != "" {
  18. fmt.Fprint(file, prompt) // Display the prompt.
  19. }
  20. password, err = getPassword()
  21. // Carriage return after the user input.
  22. fmt.Fprintln(file, "")
  23. return
  24. }
  25. func readline() (value string, err error) {
  26. var valb []byte
  27. var n int
  28. b := make([]byte, 1)
  29. for {
  30. // read one byte at a time so we don't accidentally read extra bytes
  31. n, err = os.Stdin.Read(b)
  32. if err != nil && err != io.EOF {
  33. return "", err
  34. }
  35. if n == 0 || b[0] == '\n' {
  36. break
  37. }
  38. valb = append(valb, b[0])
  39. }
  40. return strings.TrimSuffix(string(valb), "\r"), nil
  41. }