cli 输入账号密码


本文摘自php中文网,作者TangYiMo,侵删。

在创建账号和密码时,需要隐藏字符串。

源码目录:

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)
}

执行:

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#

相关阅读 >>

Golang 是面向对象还是面向过程?

手撸Golang Go与微服务 聚合模式之2

Golang垃圾回收机制

Golang web开发乱码的原因与解决方法

Golang 空指针怎么检查

Go中x/sync/semaphore解读

dbatool-dodba

Golang cond基本用法

Golang如何编译

Golang文件复制

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...