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#

相关阅读 >>

24 Goroutine channel实现并发和并行(一)

Golang如何捕获错误

Golang用户登录怎么做

Golang源代码阅读,sync系列-once

分享一个Go json 踩坑记录

Go 语言 协程和管道讲解

Go语言指针

Go 每日一库之 termtables

Golang不开发gui吗

Golang Gopath如何设置

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




打赏

取消

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

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

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

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

评论

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