backive/events/events.go

62 lines
1.1 KiB
Go
Raw Normal View History

2021-10-27 23:05:36 +02:00
package events
2021-11-14 15:07:20 +01:00
import (
"encoding/json"
"io"
"net"
)
var ls net.Listener
var done <-chan struct{}
2021-11-14 15:07:20 +01:00
var callbacks := make([]func(map[string]string), 3)
2021-11-14 15:07:20 +01:00
// Init initializes the unix socket.
func Init(socketPath string) {
ls, err = net.Listen(socketPath)
if err != nil {
panic(err)
}
}
2021-11-14 15:07:20 +01:00
// Listen starts the event loop.
func Listen() {
for {
go func() {
process()
}()
}
2021-11-14 15:07:20 +01:00
}
2021-11-14 15:07:20 +01:00
// RegisterCallback adds a function to the list of callback functions for processing of events.
func RegisterCallback(cb func(map[string]string)){
append(callbacks, cb)
}
2021-11-14 15:07:20 +01:00
// process processes each and every unix socket event, Unmarshals the json data and calls the list of callbacks.
func process() {
client, err = ls.Accept()
if err != nil {
panic(err)
}
2021-11-14 15:07:20 +01:00
data := make([]byte, 2048)
for {
buf := make([]byte, 512)
nr, err := client.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
append(data, buf[0:nr])
if err == io.EOF {
break
}
}
env := map[string]string{}
err := json.Unmarshal(data, &env)
if err != nil {
2021-11-14 15:07:20 +01:00
panic(err)
}
for _, v = range(callbacks) {
v(env)
}
}