-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout.go
More file actions
45 lines (40 loc) · 867 Bytes
/
Copy pathtimeout.go
File metadata and controls
45 lines (40 loc) · 867 Bytes
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
package wu
import (
"bufio"
"fmt"
"os"
"strings"
"time"
)
// TimeoutYesOrNo prompts the user for a yes/no answer with a timeout.
// Returns the defaultResult if the timeout expires or an invalid input is given.
func TimeoutYesOrNo(desc string, timeout time.Duration, defaultResult bool) bool {
fmt.Printf("%s [y/n]: ", desc)
done := make(chan bool, 1)
var result bool
go func() {
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err == nil {
input = strings.TrimSpace(strings.ToLower(input))
switch input {
case "y", "yes":
result = true
case "n", "no":
result = false
default:
result = defaultResult
}
} else {
result = defaultResult
}
done <- true
}()
select {
case <-done:
return result
case <-time.After(timeout):
fmt.Println("\nTimeout!")
return defaultResult
}
}