timetable-mgr/messaging/client.go

55 lines
1.4 KiB
Go

package messaging
import (
"time"
"git.fjla.uk/owlboard/timetable-mgr/helpers"
"git.fjla.uk/owlboard/timetable-mgr/log"
"github.com/go-stomp/stomp/v3"
)
var Client *stomp.Conn
// Initialises the connection to the STOMP server
func StompInit(cfg *helpers.Configuration) {
Client = dial(cfg.NrodUser, cfg.NrodPass)
}
// Connects the STOMP file to the Network Rail MQ Server
func dial(user, pass string) *stomp.Conn {
conn, err := stomp.Dial("tcp", "publicdatafeeds.networkrail.co.uk:61618",
stomp.ConnOpt.Login(user, pass),
stomp.ConnOpt.HeartBeat(15*time.Second, 15*time.Second),
stomp.ConnOpt.Header("client-id", user+"-mq-client"),
)
if err != nil {
log.Fatal("Unable to connect to STOMP Client: " + err.Error())
conn.Disconnect()
}
log.Info("Initialised STOMP Client")
return conn
}
// Handles graceful disconnection of the STOMP client, falls back to
// a force disconnect if this fails.
func Disconnect(conn *stomp.Conn) {
if conn != nil {
err := conn.Disconnect()
log.Warn("Disconnected STOMP Client")
if err != nil {
conn.MustDisconnect()
log.Error("STOMP Disconnection failed, forced disconnect")
}
return
}
log.Error("STOMP Disconnect failed, next connection attempt may fail")
err := Client.Disconnect()
if err != nil {
Client.MustDisconnect()
log.Warn("STOMP Disconnect failed, forced disconnection")
}
log.Info("STOMP Client disconnected")
}