-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompt4Types.go
95 lines (81 loc) · 1.91 KB
/
prompt4Types.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// helperFunctions
// Written by J.F. Gratton <jean-francois@famillegratton.net>
// Original filename: /prompt4Type.go
// Original timestamp: 2024/04/10 15:23
package helperFunctions
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// Getting typed values from prompt
func GetStringValFromPrompt(prompt string) string {
inputScanner := bufio.NewScanner(os.Stdin)
fmt.Printf("%s", prompt)
inputScanner.Scan()
nval := inputScanner.Text()
value := ""
if nval != "" {
value = nval
}
return value
}
func GetIntValFromPrompt(prompt string) int {
var err error
value := 0
inputScanner := bufio.NewScanner(os.Stdin)
fmt.Printf("%s", prompt)
inputScanner.Scan()
nval := inputScanner.Text()
if nval != "" {
value, err = strconv.Atoi(nval)
if err != nil {
value = 1
}
}
return value
}
func GetBoolValFromPrompt(prompt string) bool {
fmt.Printf("%s", prompt)
bval := ""
var value = false
fmt.Scanln(&bval)
if strings.HasPrefix(strings.ToLower(bval), "t") || bval == "1" {
value = true
}
return value
}
func GetStringSliceFromPrompt(prompt string) []string {
slice := []string{}
scanner := bufio.NewScanner(os.Stdin)
fmt.Printf("%s\n", prompt)
for {
fmt.Println("Just press enter to end the loop")
scanner.Scan()
input := scanner.Text()
if input == "" {
break
} else {
slice = append(slice, input)
}
}
return slice
}
// This one is more generic in the sense that it should be used whenever
// We cannot know before run-time what type of value should be expected
func GetValueFromPrompt(prompt string) interface{} {
input := GetStringValFromPrompt(prompt)
if num, err := strconv.ParseUint(input, 10, 64); err == nil {
return uint(num)
}
if num, err := strconv.ParseInt(input, 10, 64); err == nil {
return int(num)
}
if val, err := strconv.ParseBool(input); err == nil {
return val
}
// If none of the above conversions work, return the input as a string
return input
}