-
Notifications
You must be signed in to change notification settings - Fork 12
/
websocket_traffic_log.go
56 lines (46 loc) · 1.29 KB
/
websocket_traffic_log.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
package enigma
import (
"encoding/json"
"io/ioutil"
"sync"
)
type (
trafficLogRow struct {
Sent json.RawMessage `json:"Sent,omitempty"`
Received json.RawMessage `json:"Received,omitempty"`
}
fileTrafficLog struct {
FileName string
Messages []trafficLogRow
mutex sync.Mutex
}
)
// Opened implements the TrafficLogger interface
func (t *fileTrafficLog) Opened() {
}
// Sent implements the TrafficLogger interface
func (t *fileTrafficLog) Sent(message []byte) {
t.mutex.Lock()
defer t.mutex.Unlock()
t.Messages = append(t.Messages, trafficLogRow{Sent: message})
}
// Received implements the TrafficLogger interface
func (t *fileTrafficLog) Received(message []byte) {
t.mutex.Lock()
defer t.mutex.Unlock()
t.Messages = append(t.Messages, trafficLogRow{Received: message})
}
// Closed implements the TrafficLogger interface
func (t *fileTrafficLog) Closed() {
bytes, _ := json.MarshalIndent(t.Messages, "", "\t")
ioutil.WriteFile(t.FileName, bytes, 0644)
}
func newFileTrafficLogger(filename string) *fileTrafficLog {
return &fileTrafficLog{FileName: filename, Messages: make([]trafficLogRow, 0, 1000)}
}
func readTrafficLog(fileName string) []trafficLogRow {
file, _ := ioutil.ReadFile(fileName)
result := []trafficLogRow{}
_ = json.Unmarshal(file, &result)
return result
}