Created
November 12, 2018 17:15
-
-
Save jrwren/7b7e6fb8c3fdc9e3cc995179b37e4b8f to your computer and use it in GitHub Desktop.
a cmdline nats client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"log" | |
"time" | |
"github.com/nats-io/go-nats" | |
) | |
func main() { | |
var publish, reply_to, request_reply, subscribe, queue string | |
count := 1 | |
var timeout time.Duration | |
flag.StringVar(&publish, "publish", "", "the channel on which to publish a message") | |
flag.StringVar(&reply_to, "reply_to", "", "the channel on which to publish a message w/reply_to") | |
flag.StringVar(&request_reply, "request_reply", "", "the channel on which to request a reply") | |
flag.StringVar(&subscribe, "subscribe", "", "the channel on which to subscribe for messages") | |
flag.StringVar(&queue, "queue", "", "the queue on which to subscribe or send") | |
flag.IntVar(&count, "count", 1, "the number of messages to receive") | |
flag.DurationVar(&timeout, "timeout", 100*time.Millisecond, "how long to wait to send or receive a single message") | |
flag.Parse() | |
nc, err := nats.Connect(nats.DefaultURL) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer nc.Flush() | |
defer nc.Close() | |
if publish != "" { | |
if err := nc.Publish(publish, []byte(flag.Arg(0))); err != nil { | |
log.Fatal(err) | |
} | |
} | |
if reply_to != "" { | |
uniqueReplyTo := nats.NewInbox() | |
sub, err := nc.SubscribeSync(uniqueReplyTo) | |
if err != nil { | |
log.Fatal(err) | |
} | |
if err := nc.PublishRequest(publish, uniqueReplyTo, []byte(flag.Arg(0))); err != nil { | |
log.Fatal(err) | |
} | |
msg, err := sub.NextMsg(timeout) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("Reply: %s", msg.Data) | |
} | |
if request_reply != "" { | |
msg, err := nc.Request(request_reply, []byte(flag.Arg(0)), timeout) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("Reply: %s", msg.Data) | |
} | |
if subscribe != "" { | |
var err error | |
var sub *nats.Subscription | |
if queue != "" { | |
sub, err = nc.QueueSubscribeSync(subscribe, queue) | |
} else { | |
sub, err = nc.SubscribeSync(subscribe) | |
} | |
if err != nil { | |
log.Fatal(err) | |
} | |
for i := 0; i < count; i++ { | |
msg, err := sub.NextMsg(timeout) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("Reply: %s", msg.Data) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment