awsnats

Connect to NATS

To connect to NATS it is necessary to use a client. NATS provides a Golang client that you can use to write a simple NATS client.

A client can produce or consume messages on a NATS subscription. This section describes how to write a client that allows us both to produce and consume messages. To do so, follow the steps below:

IMPORTANT: To follow the steps below, you need to have the Go environment set up. See the Go official documentation to learn how to install Go.

  • Obtain the NATS server authentication credentials.

  • Create a file named nats-client.go including the following content:

      package main
      import (
          "flag"
          "fmt"
          "log"
          "runtime"
          "github.com/nats-io/go-nats"
      )
    
      func usage_prod() {
          log.Fatalf("Usage: nats-pub [-s server (%s)] [-u user (%s)] [-p password (%s)] -c produce <subject> <msg> \n", nats.DefaultURL, "nats", "S3Cr3TP@5w0rD")
      }
    
      func usage_con() {
          log.Fatalf("Usage: nats-pub [-s server (%s)] [-u user (%s)] [-p password (%s)] -c consume <subject> \n", nats.DefaultURL, "nats", "S3Cr3TP@5w0rD")
      }
    
      func main() {
          var urls = flag.String("s", nats.DefaultURL, "The nats server URLs (separated by comma)")
          var authUser = flag.String("u", "nats", "The nats server authentication user for clients")
          var authPassword = flag.String("p", "", "The nats server authentication password for clients")
          var command = flag.String("c", "", "Whether to produce or consume a message")
          log.SetFlags(0)
          flag.Parse()
          args := flag.Args()
          if *command == "" {
              log.Fatalf("Error: Indicate the command using '-command' flag")
          }
          if *command != "produce" && *command != "consume" {
              log.Fatalf("Error: Supported commands are: consume & produce")
          }
          nc, err := nats.Connect(*urls, nats.UserInfo(*authUser, *authPassword))
          if err != nil {
              log.Fatal(err)
          }
          fmt.Println("Connected to NATS server: " + *urls)
          if *command == "produce" {
              if len(args) < 2 {
                  usage_prod()
              }
              subj, msg := args[0], []byte(args[1])
              nc.Publish(subj, msg)
              nc.Flush()
              if err := nc.LastError(); err != nil {
                  log.Fatal(err)
              } else {
                  log.Printf("Published [%s] : '%s'\n", subj, msg)
              }
          }
          if *command == "consume" {
              if len(args) < 1 {
                      usage_con()
              }
              subj := args[0]
              nc.Subscribe(subj, func(msg *nats.Msg) {
                  log.Printf("Received message '%s\n", string(msg.Data)+"'")
              })
              nc.Flush()
              if err := nc.LastError(); err != nil {
                  log.Fatal(err)
              }
              log.Printf("Listening on [%s]\n", subj)
              runtime.Goexit()
          }
      }
    
  • Use the client to create a subscriber. Replace the PASSWORD placeholder with the credentials you have obtained in the NATS authentication section:

      $ go run nats-client.go -s nats://127.0.0.1:4222 -u nats -p PASSWORD -c consume foo
    
  • Use the client to send a message to the subject “foo”. Replace the PASSWORD placeholder with the credentials you have obtained in the NATS authentication section:

      $ go run nats-client.go -s nats://127.0.0.1:4222 -u nats -p PASSWORD -c produce foo bar
      Connected to NATS server: nats://127.0.0.1:4222
      Published [foo] : 'bar'
    
  • You should see the confirmation of the subscriber is receiving the messages:

      Listening on [foo]
      ...
      Received message 'bar'
    

To learn more about the use of this and other clients, check NATS official documentation and NATS GitHub repository.

Last modification March 24, 2021