Example #1
10
func main() {
	var ns *nats.Conn
	var err error
	const maxWait = 30

	i := 0
	for ; i < maxWait; i++ {
		ns, err = nats.Connect(os.Getenv("NATS_URI"))
		if err == nil {
			break
		}
		time.Sleep(1 * time.Second)
	}
	if err != nil {
		log.Fatalln("nats.Connect:", err)
	}

	defer ns.Close()

	subReader, err := ns.SubscribeSync("nats-cast")
	if err != nil {
		log.Fatalln("nats.SubscribeSync:", err)
	}

	fmt.Println("waiting for messages from cast-server...")
	for {
		msg, err := subReader.NextMsg(5 * time.Minute)
		if err == nats.ErrConnectionClosed {
			return
		} else if err != nil {
			log.Fatal(err)
		}
		fmt.Println(string(msg.Data))
	}
}
Example #2
0
func NewElectronConn(opt *nats.Options) (ec *ElectronConn, err error) {
	var nc *nats.Conn
	if opt == nil {
		nc, err = nats.Connect(nats.DefaultURL)
	} else {
		nc, err = opt.Connect()
	}
	if err != nil {
		return nil, err
	}

	ec = &ElectronConn{conn: nc}
	f := func(m *nats.Msg) {
		ID := atomic.AddUint32(&ec.genID, 1)
		if err := nc.Publish(m.Reply, []byte(fmt.Sprintf("%d", ID))); err != nil {
			logrus.Error(err)
			return
		}
		ec.Lock()
		ec.clients = append(ec.clients, ID)
		ec.Unlock()
	}
	if _, err = nc.Subscribe("register", f); err != nil {
		nc.Close()
		return nil, fmt.Errorf("nats: %v", err)
	}

	if ec.jsonConn, err = nats.NewEncodedConn(nc, "json"); err != nil {
		nc.Close()
		return nil, fmt.Errorf("nats: %v", err)
	}
	return
}