0

I have a sample program to accept passwords on my terminal, and I'm using the terminal package for this. However, when I press any of the arrow keys by mistake while inputting my password I get some weird errors.

I wanted to separate my input password and then only use that for authorization. The following is what I tried.

My input string is

// Accept password using terminal.ReadPassword() which returns []byte
// password entered is "\x1b[Aabcd"
// where \x1b[A is the up arrow key and abcd is my input entry. 

for _, c := range bytes.Runes(password) {
                if !unicode.IsPrint(c) {
                    fmt.Printf("\nINVALID PWD ")
                } else {
                    d = append(d, c)
                }
            }
fmt.Println("\n\n", fmt.Sprintf("%c", d))

Here it prints [Aabcd in the end.

Is there anyway I can only capture/print the input characters without the [A here ?

Thanks

kbinstance
  • 346
  • 5
  • 17

1 Answers1

0

1- If you need to separate the control sequence from input string, You may use unicode.IsControl(r):

IsControl reports whether the rune is a control character. The C (Other) Unicode category includes more code points such as surrogates; use Is(C, r) to test for them.

2- Also See: getpasswd functionality in Go?

package main

import "fmt"
import "github.com/howeyc/gopass"

func main() {
    fmt.Printf("Password: ")
    pass := gopass.GetPasswd()
    // Do something with pass
}

3- instead of for _, c := range bytes.Runes(password) { you may use: for _, r := range password {, as the following code:

d := make([]rune, 0, utf8.RuneCount([]byte(password)))
for _, r := range password {
    if !unicode.IsControl(r) {
        d = append(d, r)
    }
}
fmt.Println(string(d))

4- Also you may use strings.Replace for VT100 codes:

password = strings.Replace(password, "\x1b[A", "", -1)

And see: http://www.ccs.neu.edu/research/gpc/MSim/vona/terminal/VT100_Escape_Codes.html

Community
  • 1
  • 1