/pub/mensageria-com-nats-e-golang.md


An Extremely Fast Messaging System with NATS and Golang

· updated 2020-02-22 · #golang

Watch the video for this article here.

Messaging with NATS

If you need several systems talking to each other with speed and simplicity, NATS is a great help. One of its most interesting traits is its incredible speed, and its simple protocol is easy to implement, so NATS shows up everywhere from IoT — there are client libraries even for Arduino — to communication between much larger services. It is also widely used in mobile applications for the same reason: a simple, fast protocol. It is a very interesting alternative to MQTT, and it is implemented in Go. :D

NATS client example

package main

import (
    "fmt"

    "github.com/nats-io/nats"
)

func main() {
    // Connect to a server
    nc, err := nats.Connect(nats.DefaultURL)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Simple Publisher
    err = nc.Publish("teste", []byte("Hello World"))
    if err != nil {
        fmt.Println(err)
        return
    }

    // Simple Async Subscriber
    _, err = nc.Subscribe("teste", func(m *nats.Msg) {
        fmt.Printf("Received a message: %s\n", string(m.Data))
    })
    if err != nil {
        fmt.Println(err)
        return
    }

    halt()
}

func halt() {
    select {}
}

Today’s source code

We meet every Thursday at 10:00 PM. To join, enter the Golang channel on Slack and look for #brazil

Cesar Gimenes


crg.eti.br · © 2026 Cesar Gimenes · CC BY 4.0 · github · pt