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

92 lines
1.9 KiB
Go
Raw Permalink Normal View History

2019-05-17 19:06:13 +05:00
package nats
import (
// stdlib
"errors"
2019-05-17 19:06:13 +05:00
"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() error {
2019-05-17 19:06:13 +05:00
log.Println("Unsuscribing from NATS topic...")
err := natsSubscription.Unsubscribe()
if err != nil {
return errors.New("ERROR unsubscribing " + Topic + " topic: " + err.Error())
2019-05-17 19:06:13 +05:00
}
if natsConn != nil {
log.Println("Closing connection to NATS...")
natsConn.Close()
}
return nil
2019-05-17 19:06:13 +05:00
}
// StartListening connects to NATS and starts to listen for messages.
func StartListening() error {
2019-05-17 19:06:13 +05:00
nc, err := nats.Connect(config.Cfg.NATS.ConnectionString)
if err != nil {
return errors.New("Failed to connect to NATS:" + err.Error())
2019-05-17 19:06:13 +05:00
}
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 {
return errors.New("Failed to subscribe to " + Topic + " topic: " + err1.Error())
2019-05-17 19:06:13 +05:00
}
natsSubscription = sub
log.Println("Subscribed to topic", Topic)
return nil
2019-05-17 19:06:13 +05:00
}