backive/events/events.go

64 lines
1.2 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-15 22:04:59 +01:00
var callbacks []func(map[string]string)
2021-11-14 15:07:20 +01:00
// Init initializes the unix socket.
func Init(socketPath string) {
2021-11-15 22:04:59 +01:00
var err error
ls, err = net.Listen("unix", socketPath)
if err != nil {
panic(err)
}
2021-11-15 22:04:59 +01:00
callbacks = make([]func(map[string]string), 3)
}
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.
2021-11-15 22:04:59 +01:00
func RegisterCallback(cb func(map[string]string)) {
callbacks = 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() {
2021-11-15 22:04:59 +01:00
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)
}
2021-11-15 22:54:36 +01:00
data = append(data, buf[0:nr]...)
2021-11-14 15:07:20 +01:00
if err == io.EOF {
break
}
}
env := map[string]string{}
2021-11-15 22:04:59 +01:00
errjson := json.Unmarshal(data, &env)
if errjson != nil {
panic(errjson)
2021-11-14 15:07:20 +01:00
}
2021-11-15 22:04:59 +01:00
for _, v := range callbacks {
2021-11-14 15:07:20 +01:00
v(env)
}
}