diff --git a/example/main.go b/example/main.go index 87f9eba..534bfb8 100644 --- a/example/main.go +++ b/example/main.go @@ -12,6 +12,7 @@ import ( func usage(w io.Writer) { io.WriteString(w, ` +login setprompt say bye @@ -19,6 +20,7 @@ bye } var completer = readline.NewPrefixCompleter( + readline.PcItem("login"), readline.PcItem("say", readline.PcItem("hello"), readline.PcItem("bye"), @@ -52,6 +54,12 @@ func main() { } switch { + case line == "login": + pswd, err := l.ReadPassword("please enter your password: ") + if err != nil { + break + } + println("you enter:", strconv.Quote(string(pswd))) case line == "help": usage(l.Stderr()) case strings.HasPrefix(line, "setprompt"): diff --git a/operation.go b/operation.go index df38e3c..b1d77e8 100644 --- a/operation.go +++ b/operation.go @@ -1,6 +1,12 @@ package readline -import "io" +import ( + "fmt" + "io" + "os" + + "golang.org/x/crypto/ssh/terminal" +) type Operation struct { cfg *Config @@ -240,6 +246,16 @@ func (o *Operation) Runes() ([]rune, error) { return r, nil } +func (o *Operation) Password(prompt string) ([]byte, error) { + w := o.Stdout() + if prompt != "" { + fmt.Fprintf(w, prompt) + } + b, err := terminal.ReadPassword(int(os.Stdin.Fd())) + fmt.Fprint(w, "\r\n") + return b, err +} + func (o *Operation) SetTitle(t string) { o.w.Write([]byte("\033[2;" + t + "\007")) } diff --git a/readline.go b/readline.go index 0501ff3..8bdebab 100644 --- a/readline.go +++ b/readline.go @@ -59,6 +59,10 @@ func (i *Instance) Stderr() io.Writer { return i.o.Stderr() } +func (i *Instance) ReadPassword(prompt string) ([]byte, error) { + return i.o.Password(prompt) +} + func (i *Instance) Readline() (string, error) { return i.o.String() }