/
root.go
120 lines (101 loc) · 2.01 KB
/
root.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package cli
import (
"bufio"
"fmt"
"os"
"sync"
"github.com/cryptounicorns/queues"
"github.com/cryptounicorns/queues/consumer"
"github.com/cryptounicorns/queues/message"
"github.com/cryptounicorns/queues/producer"
"github.com/cryptounicorns/queues/queue/websocket"
"github.com/cryptounicorns/queues/result"
"github.com/urfave/cli"
)
var (
// RootCommands is a list of subcommands for the application.
RootCommands = []cli.Command{}
// RootFlags is a list of flags for the application.
RootFlags = []cli.Flag{
cli.BoolFlag{
Name: "debug",
Usage: "add this flag to enable debug mode",
},
cli.BoolFlag{
Name: "profile",
Usage: "write profile information for debugging",
},
}
)
// RootAction is executing when program called without any subcommand.
func RootAction(c *cli.Context) error {
var (
wg = &sync.WaitGroup{}
q queues.Queue
cr consumer.Consumer
pr producer.Producer
err error
)
if len(c.Args()) == 0 {
log.Fatal("You should specify an endpoint address in a format <scheme>://<hostname>[:port][/path]")
}
q = websocket.FromConfig(
websocket.Config{Addr: c.Args().Get(0)},
log,
)
defer q.Close()
cr, err = q.Consumer()
if err != nil {
log.Fatal(err)
}
defer cr.Close()
pr, err = q.Producer()
if err != nil {
log.Fatal(err)
}
defer pr.Close()
go func() {
defer wg.Done()
var (
stream <-chan result.Result
err error
)
stream, err = cr.Consume()
if err != nil {
log.Fatal(err)
}
for r := range stream {
switch {
case r.Err != nil:
log.Fatal(r.Err)
default:
log.Debugf("Consumed: %s", r.Value)
fmt.Printf("%s\n", r.Value)
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
var (
s = bufio.NewScanner(os.Stdin)
m message.Message
err error
)
for s.Scan() {
m = message.Message(s.Text())
log.Debugf("Producing: %s", m)
err = pr.Produce(m)
if err != nil {
log.Fatal(err)
}
}
err = s.Err()
if err != nil {
log.Fatal(err)
}
}()
wg.Add(1)
wg.Wait()
return nil
}