forked from ECSC2022/ctf-gameserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipc.go
69 lines (58 loc) · 1.12 KB
/
ipc.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
// Communication with checkermaster
package checkerlib
import (
"bufio"
"bytes"
"encoding/json"
"io"
"sync"
)
type ipcData struct {
sync.Mutex
in *bufio.Scanner
out io.Writer
}
func (i *ipcData) Send(action string, param interface{}) {
ipc.Lock()
defer ipc.Unlock()
i.send(action, param)
}
func (i *ipcData) SendRecv(action string, param interface{}) interface{} {
ipc.Lock()
defer ipc.Unlock()
i.send(action, param)
return i.recv()
}
func (i *ipcData) send(action string, param interface{}) {
data := struct {
Action string `json:"action"`
Param interface{} `json:"param"`
}{
action,
param,
}
x, err := json.Marshal(data)
if err != nil {
panic(err)
}
// Make sure that our JSON consists of just a single line as required
// by IPC protocol
x = append(bytes.Replace(x, []byte{'\n'}, nil, -1), '\n')
_, err = i.out.Write(x)
if err != nil {
panic(err)
}
}
func (i *ipcData) recv() interface{} {
if !i.in.Scan() {
panic(i.in.Err())
}
var x struct {
Response interface{} `json:"response"`
}
err := json.Unmarshal(i.in.Bytes(), &x)
if err != nil {
panic(err)
}
return x.Response
}