> 在创建账号和密码时,需要隐藏字符串。
源码目录:
```shell
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"github.com/howeyc/gopass"
)
// GetPassword ask user for password interactively
func GetPassword() (string, error) {
fmt.Printf("Please input your key file password: ")
pass, err := gopass.GetPasswd()
if err != nil {
return "", err
}
return string(pass), nil
}
// SetPassword ask user input password twice and get the password interactively
func SetPassword() (string, error) {
fmt.Printf("Password: ")
pass, err := gopass.GetPasswd()
if err != nil {
return "", err
}
fmt.Printf("Repeat password:")
passRepeat, err := gopass.GetPasswd()
if err != nil {
return "", err
}
if !bytes.Equal(pass, passRepeat) {
return "", errors.New("twice input passwd is not match")
}
return string(pass), nil
}
func getInput() ([]byte, error) {
r := bufio.NewReader(os.Stdin)
d, err := r.ReadBytes('\n')
d = d[:len(d)-1]
return d, err
}
func main() {
fmt.Println("please input user:")
user, err := getInput()
if err != nil {
fmt.Println(err)
return
}
passwd, err := SetPassword()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(user), passwd)
}
```
执行:
```shell
root@jack-VirtualBox:~/test/passwd-input# go mod init tt
root@jack-VirtualBox:~/test/passwd-input# go mod tidy
root@jack-VirtualBox:~/test/passwd-input# go build
root@jack-VirtualBox:~/test/passwd-input# ./tt
please input user:
jack
Password:
Repeat password:
jack 123456
root@jack-VirtualBox:~/test/passwd-input#
```
有疑问加站长微信联系(非本文作者))