Home >Backend Development >Golang >How to Simulate `getpasswd` Functionality in Go?
How to Implement getpasswd Functionality in Go?
In Go, there is no built-in function similar to getpasswd that allows you to read a password from stdin without echoing it to the terminal. However, there are techniques you can use to achieve similar functionality.
Best Practice Solution
The recommended approach is to use a combination of Go packages:
import ( "bufio" "fmt" "golang.org/x/term" )
Step 1: Read Username
fmt.Print("Enter Username: ") username, _ := bufio.NewReader(os.Stdin).ReadString('\n')
Step 2: Read Password (Without Echo)
fmt.Print("Enter Password: ") bytePassword, _ := term.ReadPassword(int(syscall.Stdin))
The term.ReadPassword() function takes the file descriptor of the standard input (stdin) and returns a slice of bytes representing the password typed by the user. It suppresses any character echo on the terminal to ensure the password remains confidential.
Step 3: Convert Bytes to String
password := string(bytePassword)
Step 4: Return Credentials
return strings.TrimSpace(username), strings.TrimSpace(password)
Example Code:
package main import ( "bufio" "fmt" "os" "strings" "syscall" "golang.org/x/term" ) func main() { username, password, _ := credentials() fmt.Printf("Username: %s, Password: %s\n", username, password) } func credentials() (string, string, error) { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter Username: ") username, err := reader.ReadString('\n') if err != nil { return "", "", err } fmt.Print("Enter Password: ") bytePassword, err := term.ReadPassword(int(syscall.Stdin)) if err != nil { return "", "", err } password := string(bytePassword) return strings.TrimSpace(username), strings.TrimSpace(password), nil }
The above is the detailed content of How to Simulate `getpasswd` Functionality in Go?. For more information, please follow other related articles on the PHP Chinese website!