Archived
1
0
This repository has been archived on 2022-06-28. You can view files and clone it, but cannot push or open issues or pull requests.
ffmpeger/nats/exported.go

88 lines
1.9 KiB
Go
Raw Normal View History

2019-05-17 19:06:13 +05:00
package nats
import (
// stdlib
"log"
"sync"
// local
"github.com/pztrn/ffmpeger/config"
// other
"github.com/nats-io/nats.go"
)
const (
Topic = "ffmpeger.v1"
)
var (
natsConn *nats.Conn
natsSubscription *nats.Subscription
// Handlers.
handlers []*Handler
handlersMutex sync.Mutex
)
// AddHandler adds handler for received NATS messages.
func AddHandler(hndl *Handler) {
handlersMutex.Lock()
handlers = append(handlers, hndl)
handlersMutex.Unlock()
}
// Initialize initializes package.
func Initialize() {
log.Println("Initializing NATS handler...")
handlers = make([]*Handler, 0, 8)
}
// Handler for NATS messages.
func messageHandler(msg *nats.Msg) {
log.Println("Received message:", string(msg.Data))
handlersMutex.Lock()
for _, hndl := range handlers {
hndl.Func(msg.Data)
}
handlersMutex.Unlock()
}
// Shutdown unsubscribes from topic and disconnects from NATS.
func Shutdown() {
log.Println("Unsuscribing from NATS topic...")
err := natsSubscription.Unsubscribe()
if err != nil {
log.Println("ERROR unsubscribing", Topic, "topic:", err.Error())
}
if natsConn != nil {
log.Println("Closing connection to NATS...")
natsConn.Close()
} else {
log.Println("Connection to NATS wasn't established")
}
}
// StartListening connects to NATS and starts to listen for messages.
func StartListening() {
nc, err := nats.Connect(config.Cfg.NATS.ConnectionString)
if err != nil {
log.Fatalln("Failed to connect to NATS:", err.Error())
}
natsConn = nc
log.Println("NATS connection established")
// Beware - if ffmpeger will be launched more than once and subscribed
// to same topic (which is hardcoded here) then ALL instances of
// ffmpeger will receive this message!
sub, err1 := nc.Subscribe(Topic, messageHandler)
if err1 != nil {
log.Fatalln("Failed to subscribe to", Topic, "topic:", err1.Error())
}
natsSubscription = sub
}