Situation:
Retrieving a password from the user without displaying the entered characters is a common requirement. How can this be achieved in Go?
Solution:
Go does not directly offer a getpasswd functionality. However, the following approach effectively accomplishes the task:
Example:
package main import ( "bufio" "fmt" "golang.org/x/term" "os" "strings" ) func main() { u, p, _ := credentials() fmt.Printf("Username: %s, Password: %s\n", u, p) } func credentials() (string, string, error) { fmt.Print("Enter Username: ") r := bufio.NewReader(os.Stdin) u, err := r.ReadString('\n') if err != nil { return "", "", err } fmt.Print("Enter Password: ") bp, err := term.ReadPassword(int(syscall.Stdin)) if err != nil { return "", "", err } p := string(bp) return strings.TrimSpace(u), strings.TrimSpace(p), nil }
This code snippet demonstrates the process of obtaining username and password from the user without displaying the password characters.
The above is the detailed content of How to Implement Non-Echoing Password Entry in Go?. For more information, please follow other related articles on the PHP Chinese website!