forked from wailsapp/wails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipc_message.go
93 lines (73 loc) · 2.27 KB
/
ipc_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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package wails
import (
"encoding/json"
"fmt"
)
// Message handler
type messageProcessorFunc func(*ipcMessage) (*ipcMessage, error)
var messageProcessors = make(map[string]messageProcessorFunc)
// ipcMessage is the struct version of the Message sent from the frontend.
// The payload has the specialised message data
type ipcMessage struct {
Type string `json:"type"`
Payload interface{} `json:"payload"`
CallbackID string `json:"callbackid,omitempty"`
sendResponse func(*ipcResponse) error
}
func parseMessage(incomingMessage string) (*ipcMessage, error) {
// Parse message
var message ipcMessage
err := json.Unmarshal([]byte(incomingMessage), &message)
return &message, err
}
func newIPCMessage(incomingMessage string, responseFunction func(*ipcResponse) error) (*ipcMessage, error) {
// Parse the Message
message, err := parseMessage(incomingMessage)
if err != nil {
return nil, err
}
// Check message type is valid
messageProcessor := messageProcessors[message.Type]
if messageProcessor == nil {
return nil, fmt.Errorf("unknown message type: %s", message.Type)
}
// Process message payload
message, err = messageProcessor(message)
if err != nil {
return nil, err
}
// Set the response function
message.sendResponse = responseFunction
return message, nil
}
// hasCallbackID checks if the message can send an error back to the frontend
func (m *ipcMessage) hasCallbackID() error {
if m.CallbackID == "" {
return fmt.Errorf("attempted to return error to message with no Callback ID")
}
return nil
}
// ReturnError returns an error back to the frontend
func (m *ipcMessage) ReturnError(format string, args ...interface{}) error {
// Ignore ReturnError if no callback ID given
err := m.hasCallbackID()
if err != nil {
return err
}
// Create response
response := newErrorResponse(m.CallbackID, fmt.Sprintf(format, args...))
// Send response
return m.sendResponse(response)
}
// ReturnSuccess returns a success message back with the given data
func (m *ipcMessage) ReturnSuccess(data interface{}) error {
// Ignore ReturnSuccess if no callback ID given
err := m.hasCallbackID()
if err != nil {
return err
}
// Create the response
response := newSuccessResponse(m.CallbackID, data)
// Send response
return m.sendResponse(response)
}