From 55b3376d4cad30e186db7a8e84d185d2e4a023fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20=C5=A0trauch?= Date: Sat, 25 Dec 2021 10:38:13 +0100 Subject: [PATCH] Reconnect instead of exit when NATS is not available --- .gitignore | 2 ++ daemon/main.go | 2 +- nats_driver/main.go | 21 +++++++++++++++------ 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 4ac8f40..7b7fa2d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +.history/ + # Files with secrets *secret* tmp/ diff --git a/daemon/main.go b/daemon/main.go index 1ffd6fe..709ee62 100644 --- a/daemon/main.go +++ b/daemon/main.go @@ -35,7 +35,7 @@ func init() { discoveryStorage.LogChannel = make(chan string) discoveryStorage.TTL = config.TTL - // localhost initization + // localhost initiation localHost = server.LocalHost{ LabelsPath: config.LabelsPath, HostnameOverride: config.HostName, diff --git a/nats_driver/main.go b/nats_driver/main.go index 2820965..15d05e1 100644 --- a/nats_driver/main.go +++ b/nats_driver/main.go @@ -3,7 +3,9 @@ package nats_driver import ( "encoding/json" "fmt" + "log" "strings" + "time" "github.com/by-cx/lobby/common" "github.com/by-cx/lobby/server" @@ -53,13 +55,20 @@ func (d *Driver) Init() error { return fmt.Errorf("please initiate LogChannel variable") } - nc, err := nats.Connect(d.NATSUrl) - if err != nil { - return err - } - d.nc = nc + var nc *nats.Conn - _, err = nc.Subscribe(d.NATSDiscoveryChannel, d.handler) + for { + nc, err := nats.Connect(d.NATSUrl) + if err != nil { + log.Println("Can't connect to the NATS server, waiting for 5 seconds before I try it again.") + time.Sleep(time.Second * 5) + continue + } + d.nc = nc + break + } + + _, err := nc.Subscribe(d.NATSDiscoveryChannel, d.handler) if err != nil { return err }