Debian Codegraph @

examples/nats-rply/main.go

raw
1 // Copyright 2012-2022 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package main
15
16 import (
17 "flag"
18 "log"
19 "os"
20 "os/signal"
21 "time"
22
23 "github.com/nats-io/nats.go"
24 )
25
26 // NOTE: Can test with demo servers.
27 // nats-rply -s demo.nats.io <subject> <response>
28
29 func usage() {
30 log.Printf("Usage: nats-rply [-s server] [-creds file] [-nkey file] [-t] [-q queue] <subject> <response>\n")
31 flag.PrintDefaults()
32 }
33
34 func showUsageAndExit(exitcode int) {
35 usage()
36 os.Exit(exitcode)
37 }
38
39 func printMsg(m *nats.Msg, i int) {
40 log.Printf("[#%d] Received on [%s]: '%s'\n", i, m.Subject, string(m.Data))
41 }
42
43 func main() {
44 var urls = flag.String("s", nats.DefaultURL, "The nats server URLs (separated by comma)")
45 var userCreds = flag.String("creds", "", "User Credentials File")
46 var nkeyFile = flag.String("nkey", "", "NKey Seed File")
47 var showTime = flag.Bool("t", false, "Display timestamps")
48 var queueName = flag.String("q", "NATS-RPLY-22", "Queue Group Name")
49 var showHelp = flag.Bool("h", false, "Show help message")
50
51 log.SetFlags(0)
52 flag.Usage = usage
53 flag.Parse()
54
55 if *showHelp {
56 showUsageAndExit(0)
57 }
58
59 args := flag.Args()
60 if len(args) < 2 {
61 showUsageAndExit(1)
62 }
63
64 // Connect Options.
65 opts := []nats.Option{nats.Name("NATS Sample Responder")}
66 opts = setupConnOptions(opts)
67
68 if *userCreds != "" && *nkeyFile != "" {
69 log.Fatal("specify -seed or -creds")
70 }
71
72 // Use UserCredentials
73 if *userCreds != "" {
74 opts = append(opts, nats.UserCredentials(*userCreds))
75 }
76
77 // Use Nkey authentication.
78 if *nkeyFile != "" {
79 opt, err := nats.NkeyOptionFromSeed(*nkeyFile)
80 if err != nil {
81 log.Fatal(err)
82 }
83 opts = append(opts, opt)
84 }
85
86 // Connect to NATS
87 nc, err := nats.Connect(*urls, opts...)
88 if err != nil {
89 log.Fatal(err)
90 }
91
92 subj, reply, i := args[0], args[1], 0
93
94 nc.QueueSubscribe(subj, *queueName, func(msg *nats.Msg) {
95 i++
96 printMsg(msg, i)
97 msg.Respond([]byte(reply))
98 })
99 nc.Flush()
100
101 if err := nc.LastError(); err != nil {
102 log.Fatal(err)
103 }
104
105 log.Printf("Listening on [%s]", subj)
106 if *showTime {
107 log.SetFlags(log.LstdFlags)
108 }
109
110 // Setup the interrupt handler to drain so we don't miss
111 // requests when scaling down.
112 c := make(chan os.Signal, 1)
113 signal.Notify(c, os.Interrupt)
114 <-c
115 log.Println()
116 log.Printf("Draining...")
117 nc.Drain()
118 log.Fatalf("Exiting")
119 }
120
121 func setupConnOptions(opts []nats.Option) []nats.Option {
122 totalWait := 10 * time.Minute
123 reconnectDelay := time.Second
124
125 opts = append(opts, nats.ReconnectWait(reconnectDelay))
126 opts = append(opts, nats.MaxReconnects(int(totalWait/reconnectDelay)))
127 opts = append(opts, nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
128 log.Printf("Disconnected due to: %s, will attempt reconnects for %.0fm", err, totalWait.Minutes())
129 }))
130 opts = append(opts, nats.ReconnectHandler(func(nc *nats.Conn) {
131 log.Printf("Reconnected [%s]", nc.ConnectedUrl())
132 }))
133 opts = append(opts, nats.ClosedHandler(func(nc *nats.Conn) {
134 log.Fatalf("Exiting: %v", nc.LastError())
135 }))
136 return opts
137 }