forked from andeya/pholcus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogsocketController.go
More file actions
99 lines (87 loc) · 1.92 KB
/
logsocketController.go
File metadata and controls
99 lines (87 loc) · 1.92 KB
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
94
95
96
97
98
99
package web
import (
ws "github.com/henrylee2cn/pholcus/common/websocket"
)
// log发送api
func wsLogHandle(conn *ws.Conn) {
var err error
sess, _ := globalSessions.SessionStart(nil, conn.Request())
sessID := sess.SessionID()
if Lsc.connPool[sessID] == nil {
Lsc.Add(sessID, conn)
}
go func() {
defer func() {
// 关闭web前端log输出并断开websocket连接
Lsc.Remove(sessID, conn)
}()
for {
if err := ws.JSON.Receive(conn, nil); err != nil {
// logs.Log.Debug("websocket log接收出错断开 (%v) !", err)
return
}
}
}()
for msg := range Lsc.lvPool[sessID].logChan {
if _, err = ws.Message.Send(conn, msg); err != nil {
return
}
}
}
type LogSocketController struct {
connPool map[string]*ws.Conn
lvPool map[string]*LogView
}
func (self *LogSocketController) Write(p []byte) (int, error) {
for sessID, lv := range self.lvPool {
if self.connPool[sessID] != nil {
lv.Write(p)
}
}
return len(p), nil
}
func (self *LogSocketController) Add(sessID string, conn *ws.Conn) {
self.connPool[sessID] = conn
self.lvPool[sessID] = newLogView()
}
func (self *LogSocketController) Remove(sessID string, conn *ws.Conn) {
defer func() {
recover()
}()
if self.connPool[sessID] == nil {
return
}
lv := self.lvPool[sessID]
lv.closed = true
close(lv.logChan)
conn.Close()
delete(self.connPool, sessID)
delete(self.lvPool, sessID)
}
var Lsc = &LogSocketController{
connPool: make(map[string]*ws.Conn),
lvPool: make(map[string]*LogView),
}
// 设置所有log输出位置为Log
type LogView struct {
closed bool
logChan chan string
}
func newLogView() *LogView {
return &LogView{
logChan: make(chan string, 1024),
closed: false,
}
}
func (self *LogView) Write(p []byte) (int, error) {
if self.closed {
goto end
}
defer func() { recover() }()
self.logChan <- (string(p) + "\r\n")
end:
return len(p), nil
}
func (self *LogView) Sprint() string {
return <-self.logChan
}