dotfiles/goagent/pkg/gophx/channel.go

46 lines
829 B
Go
Raw Normal View History

2024-02-15 13:25:45 +00:00
package gophx
2024-02-17 15:20:08 +00:00
type Channel struct {
topic string
bindings map[string]func(any)
}
2024-02-15 13:25:45 +00:00
2024-02-17 15:20:08 +00:00
func NewChannel(topic string, params any, socket *Socket) *Channel {
// TODO: rejoin when socket is reconnected
channel := &Channel{
bindings: make(map[string]func(any)),
topic: topic,
}
2024-02-15 13:25:45 +00:00
2024-02-17 15:20:08 +00:00
msg := message{
joinRef: 0,
ref: 0,
topic: topic,
event: "phx_join",
payload: params,
}
2024-02-15 13:25:45 +00:00
2024-02-17 15:20:08 +00:00
data, err := msg.serializeJSON()
2024-02-15 13:25:45 +00:00
if err != nil {
2024-02-17 15:20:08 +00:00
panic(err)
2024-02-15 13:25:45 +00:00
}
2024-02-17 15:20:08 +00:00
socket.addChannel(channel)
socket.send(data)
return channel
}
func (channel *Channel) On(event string, callback func(any)) {
channel.bindings[event] = callback
}
func (channel *Channel) Push(event string, params any) {
2024-02-15 13:25:45 +00:00
2024-02-17 15:20:08 +00:00
}
func (channel *Channel) handleMessage(msg message) {
if binding, ok := channel.bindings[msg.event]; ok {
go binding(msg.payload)
}
2024-02-15 13:25:45 +00:00
}