-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmain.go
61 lines (51 loc) · 1.09 KB
/
main.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
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"time"
)
var totalDuration time.Duration = 5
func getName(r io.Reader, w io.Writer) (string, error) {
scanner := bufio.NewScanner(r)
msg := "Your name please? Press the Enter key when done"
fmt.Fprintln(w, msg)
scanner.Scan()
if err := scanner.Err(); err != nil {
return "", err
}
name := scanner.Text()
if len(name) == 0 {
return "", errors.New("You entered an empty name")
}
return name, nil
}
func getNameContext(ctx context.Context) (string, error) {
var err error
name := "Default Name"
c := make(chan error, 1)
go func() {
name, err = getName(os.Stdin, os.Stdout)
c <- err
}()
select {
case <-ctx.Done():
return name, ctx.Err()
case err := <-c:
return name, err
}
}
func main() {
allowedDuration := totalDuration * time.Second
ctx, cancel := context.WithTimeout(context.Background(), allowedDuration)
defer cancel()
name, err := getNameContext(ctx)
if err != nil && !errors.Is(err, context.DeadlineExceeded) {
fmt.Fprintf(os.Stdout, "%v\n", err)
os.Exit(1)
}
fmt.Fprintln(os.Stdout, name)
}