-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmain.go
86 lines (77 loc) · 1.58 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
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
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"io"
"os"
)
type config struct {
numTimes int
}
func getName(r io.Reader, w io.Writer) (string, error) {
scanner := bufio.NewScanner(r)
msg := "Your name please? Press the Enter key when done.\n"
fmt.Fprintf(w, msg)
scanner.Scan()
if err := scanner.Err(); err != nil {
return "", err
}
name := scanner.Text()
if len(name) == 0 {
return "", errors.New("You didn't enter your name")
}
return name, nil
}
func greetUser(c config, name string, w io.Writer) {
msg := fmt.Sprintf("Nice to meet you %s\n", name)
for i := 0; i < c.numTimes; i++ {
fmt.Fprintf(w, msg)
}
}
func runCmd(r io.Reader, w io.Writer, c config) error {
name, err := getName(r, w)
if err != nil {
return err
}
greetUser(c, name, w)
return nil
}
func validateArgs(c config) error {
if !(c.numTimes > 0) {
return errors.New("Must specify a number greater than 0")
}
return nil
}
func parseArgs(w io.Writer, args []string) (config, error) {
c := config{}
fs := flag.NewFlagSet("greeter", flag.ContinueOnError)
fs.SetOutput(w)
fs.IntVar(&c.numTimes, "n", 0, "Number of times to greet")
err := fs.Parse(args)
if err != nil {
return c, err
}
if fs.NArg() != 0 {
return c, errors.New("Positional arguments specified")
}
return c, nil
}
func main() {
c, err := parseArgs(os.Stderr, os.Args[1:])
if err != nil {
fmt.Fprintln(os.Stdout, err)
os.Exit(1)
}
err = validateArgs(c)
if err != nil {
fmt.Fprintln(os.Stdout, err)
os.Exit(1)
}
err = runCmd(os.Stdin, os.Stdout, c)
if err != nil {
fmt.Fprintln(os.Stdout, err)
os.Exit(1)
}
}