This repository has been archived by the owner on Feb 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
message.go
70 lines (61 loc) · 1.7 KB
/
message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package bootstrap
import (
"encoding/json"
"fmt"
"github.com/asticode/go-astikit"
"github.com/asticode/go-astilectron"
)
// MessageOut represents a message going out
type MessageOut struct {
Name string `json:"name"`
Payload interface{} `json:"payload,omitempty"`
}
// MessageIn represents a message going in
type MessageIn struct {
Name string `json:"name"`
Payload json.RawMessage `json:"payload,omitempty"`
}
func handleMessages(w *astilectron.Window, messageHandler MessageHandler, l astikit.SeverityLogger) astilectron.ListenerMessage {
return func(m *astilectron.EventMessage) (v interface{}) {
// Unmarshal message
var i MessageIn
var err error
if err = m.Unmarshal(&i); err != nil {
l.Error(fmt.Errorf("unmarshaling message %+v failed: %w", *m, err))
return
}
// Handle message
var p interface{}
if p, err = messageHandler(w, i); err != nil {
l.Error(fmt.Errorf("handling message %+v failed: %w", i, err))
}
// Return message
if p != nil {
o := &MessageOut{Name: i.Name + ".callback", Payload: p}
if err != nil {
o.Name = "error"
}
v = o
}
return
}
}
// CallbackMessage represents a bootstrap message callback
type CallbackMessage func(m *MessageIn)
// SendMessage sends a message
func SendMessage(w *astilectron.Window, name string, payload interface{}, cs ...CallbackMessage) error {
var callbacks []astilectron.CallbackMessage
for _, c := range cs {
callbacks = append(callbacks, func(e *astilectron.EventMessage) {
var m *MessageIn
if e != nil {
m = &MessageIn{}
if err := e.Unmarshal(m); err != nil {
return
}
}
c(m)
})
}
return w.SendMessage(MessageOut{Name: name, Payload: payload}, callbacks...)
}