/
read_stdin.go
50 lines (45 loc) · 993 Bytes
/
read_stdin.go
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
47
48
49
50
package main
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"golang.org/x/term"
)
func readPasswordStdin() string {
bytePassword, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
panic(err)
}
return string(bytePassword)
}
func readLineFromStdin(isPassword bool) string {
var text string
if isPassword {
text = readPasswordStdin()
} else {
var err error
reader := bufio.NewReader(os.Stdin)
text, err = reader.ReadString('\n')
if err != nil {
panic(err)
}
}
text = strings.TrimSpace(text)
return text
}
func doubleReadInput(prefix string, isPassword bool, failedAttempts int) string {
for i := failedAttempts; i > 0; i-- {
fmt.Print(prefix)
text1 := readLineFromStdin(isPassword)
fmt.Println("\nEnter it again")
fmt.Print(prefix)
text2 := readLineFromStdin(isPassword)
if text1 == text2 {
return text1
}
fmt.Println("\nInputs do not match. Please try again.")
}
panic("failed reading the input. failed too many times.")
}