-
Notifications
You must be signed in to change notification settings - Fork 194
/
main.go
66 lines (58 loc) · 1.34 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
package main
import (
"context"
"flag"
"fmt"
"os"
"strings"
"github.com/campoy/justforfunc/31-grpc/todo"
grpc "google.golang.org/grpc"
)
func main() {
flag.Parse()
if flag.NArg() < 1 {
fmt.Fprintln(os.Stderr, "missing subcommand: list or add")
os.Exit(1)
}
conn, err := grpc.Dial(":8888", grpc.WithInsecure())
if err != nil {
fmt.Fprintf(os.Stderr, "could not connect to backend: %v\n", err)
os.Exit(1)
}
client := todo.NewTasksClient(conn)
switch cmd := flag.Arg(0); cmd {
case "list":
err = list(context.Background(), client)
case "add":
err = add(context.Background(), client, strings.Join(flag.Args()[1:], " "))
default:
err = fmt.Errorf("unknown subcommand %s", cmd)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func add(ctx context.Context, client todo.TasksClient, text string) error {
_, err := client.Add(ctx, &todo.Text{Text: text})
if err != nil {
return fmt.Errorf("could not add task in the backend: %v", err)
}
fmt.Println("task added successfully")
return nil
}
func list(ctx context.Context, client todo.TasksClient) error {
l, err := client.List(ctx, &todo.Void{})
if err != nil {
return fmt.Errorf("could not fetch tasks: %v", err)
}
for _, t := range l.Tasks {
if t.Done {
fmt.Printf("👍")
} else {
fmt.Printf("😱")
}
fmt.Printf(" %s\n", t.Text)
}
return nil
}