-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (81 loc) · 2.35 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"context"
"fmt"
"os"
"runtime"
rd "runtime/debug"
"time"
log "github.com/sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
piper *kingpin.Application
debug bool
async bool
nctx string
name string
notifier *kingpin.CmdClause
notifierMessage string
notifierTimeout time.Duration
listener *kingpin.CmdClause
listenGroup bool
)
func main() {
piper = kingpin.New("piper", "Network pipes")
piper.Version(getVersion())
piper.Flag("context", "NATS context to use for connection").Envar("PIPER_CONTEXT").Default("piper").StringVar(&nctx)
piper.Flag("async", "Operates asynchronously using JetStream work queues").Envar("PIPER_ASYNC").Short('a').BoolVar(&async)
piper.Flag("timeout", "How long to wait for a listener to login before giving up").Envar("PIPER_TIMEOUT").DurationVar(¬ifierTimeout)
piper.Flag("debug", "Enable debug logging").BoolVar(&debug)
listener = piper.Command("listen", "Listen for messages on the pipe")
listener.Arg("name", "Pipe name to wait on for a message").Required().StringVar(&name)
listener.Flag("group", "Listen on a group").BoolVar(&listenGroup)
notifier = piper.Command("notify", "Notifies listeners").Default()
notifier.Arg("name", "Pipe name to publish a message to").Required().StringVar(&name)
notifier.Arg("message", "The message to sent, reads STDIN otherwise").StringVar(¬ifierMessage)
piper.Command("setup", "Creates JetStream configuration to enable asynchronous functionality")
command := kingpin.MustParse(piper.Parse(os.Args[1:]))
var err error
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
log.SetOutput(os.Stderr)
if debug {
log.SetLevel(log.DebugLevel)
}
switch command {
case "listen":
err = NewListener().Listen(ctx)
case "notify":
err = NewNotifier().Notify(ctx)
case "setup":
err = asyncSetup()
default:
err = fmt.Errorf("invalid command %s", command)
}
if err != nil {
fmt.Fprintf(os.Stderr, "failed to run: %v\n", err)
cancel()
runtime.Goexit()
}
}
func asyncSetup() error {
nc, err := connect(nctx)
if err != nil {
return err
}
defer nc.Close()
_, err = createStream(2*time.Second, nc)
if err != nil {
return err
}
log.Info("Created 'PIPER' Stream")
return nil
}
func getVersion() string {
mods, ok := rd.ReadBuildInfo()
if !ok {
return "development"
}
return mods.Main.Version
}