使用 Go CLI 詢問帳號密碼

做法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main

import (
"bufio"
"fmt"
"log"
"os"
"strings"
"syscall"

"golang.org/x/crypto/ssh/terminal"
)

type Credentials struct {
Username string
Password string
}

func main() {
c, err := NewCredentials()
if err != nil {
log.Println(err.Error())
}
fmt.Printf("\nUsername: %s, Password: %s\n", c.Username, c.Password)
}

func NewCredentials() (*Credentials, error) {
c := &Credentials{}
reader := bufio.NewReader(os.Stdin)

fmt.Print("Enter Username: ")
username, err := reader.ReadString('\n')
if err != nil {
return nil, err
}
c.Username = strings.TrimSpace(username)

fmt.Print("Enter Password: ")
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
return nil, err
}
c.Password = string(bytePassword)

return c, nil
}