Debian Codegraph @

examples/nats-sub/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 "runtime"
21 "time"
22
23 "github.com/nats-io/nats.go"
24 )
25
26 // NOTE: Can test with demo servers.
27 // nats-sub -s demo.nats.io <subject>
28
29 func usage() {
30 log.Printf("Usage: nats-sub [-s server] [-creds file] [-nkey file] [-tlscert file] [-tlskey file] [-tlscacert file] [-t] <subject>\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'", 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 tlsClientCert = flag.String("tlscert", "", "TLS client certificate file")
48 var tlsClientKey = flag.String("tlskey", "", "Private key file for client certificate")
49 var tlsCACert = flag.String("tlscacert", "", "CA certificate to verify peer against")
50 var showTime = flag.Bool("t", false, "Display timestamps")
51 var showHelp = flag.Bool("h", false, "Show help message")
52
53 log.SetFlags(0)
54 flag.Usage = usage
55 flag.Parse()
56
57 if *showHelp {
58 showUsageAndExit(0)
59 }
60
61 args := flag.Args()
62 if len(args) != 1 {
63 showUsageAndExit(1)
64 }
65
66 // Connect Options.
67 opts := []nats.Option{nats.Name("NATS Sample Subscriber")}
68 opts = setupConnOptions(opts)
69
70 if *userCreds != "" && *nkeyFile != "" {
71 log.Fatal("specify -seed or -creds")
72 }
73
74 // Use UserCredentials
75 if *userCreds != "" {
76 opts = append(opts, nats.UserCredentials(*userCreds))
77 }
78
79 // Use TLS client authentication
80 if *tlsClientCert != "" && *tlsClientKey != "" {
81 opts = append(opts, nats.ClientCert(*tlsClientCert, *tlsClientKey))
82 }
83
84 // Use specific CA certificate
85 if *tlsCACert != "" {
86 opts = append(opts, nats.RootCAs(*tlsCACert))
87 }
88
89 // Use Nkey authentication.
90 if *nkeyFile != "" {
91 opt, err := nats.NkeyOptionFromSeed(*nkeyFile)
92 if err != nil {
93 log.Fatal(err)
94 }
95 opts = append(opts, opt)
96 }
97
98 // Connect to NATS
99 nc, err := nats.Connect(*urls, opts...)
100 if err != nil {
101 log.Fatal(err)
102 }
103
104 subj, i := args[0], 0
105
106 nc.Subscribe(subj, func(msg *nats.Msg) {
107 i += 1
108 printMsg(msg, i)
109 })
110 nc.Flush()
111
112 if err := nc.LastError(); err != nil {
113 log.Fatal(err)
114 }
115
116 log.Printf("Listening on [%s]", subj)
117 if *showTime {
118 log.SetFlags(log.LstdFlags)
119 }
120
121 runtime.Goexit()
122 }
123
124 func setupConnOptions(opts []nats.Option) []nats.Option {
125 totalWait := 10 * time.Minute
126 reconnectDelay := time.Second
127
128 opts = append(opts, nats.ReconnectWait(reconnectDelay))
129 opts = append(opts, nats.MaxReconnects(int(totalWait/reconnectDelay)))
130 opts = append(opts, nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
131 log.Printf("Disconnected due to:%s, will attempt reconnects for %.0fm", err, totalWait.Minutes())
132 }))
133 opts = append(opts, nats.ReconnectHandler(func(nc *nats.Conn) {
134 log.Printf("Reconnected [%s]", nc.ConnectedUrl())
135 }))
136 opts = append(opts, nats.ClosedHandler(func(nc *nats.Conn) {
137 log.Fatalf("Exiting: %v", nc.LastError())
138 }))
139 return opts
140 }