-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathngserver.go
More file actions
174 lines (153 loc) · 3.64 KB
/
ngserver.go
File metadata and controls
174 lines (153 loc) · 3.64 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/*Package ngserver get the captured http data from ngnet,
and send these data to frontend by websocket.
chan +-----NGClient
ngnet----------NGServer---------+-----NGClient
+-----NGClient
*/
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"sync"
"github.com/ga0/netgraph/web"
"golang.org/x/net/websocket"
)
// NGClient is the websocket client
type NGClient struct {
eventChan chan interface{}
server *NGServer
ws *websocket.Conn
}
func (c *NGClient) recvAndProcessCommand() {
for {
var msg string
err := websocket.Message.Receive(c.ws, &msg)
if err != nil {
return
}
if len(msg) > 0 {
if msg == "sync" {
c.server.sync(c)
}
} else {
panic("empty command")
}
}
}
func (c *NGClient) transmitEvents() {
for ev := range c.eventChan {
json, err := json.Marshal(ev)
if err == nil {
websocket.Message.Send(c.ws, string(json))
}
}
}
func (c *NGClient) close() {
close(c.eventChan)
}
// NewNGClient creates NGClient
func NewNGClient(ws *websocket.Conn, server *NGServer) *NGClient {
c := new(NGClient)
c.server = server
c.ws = ws
c.eventChan = make(chan interface{}, 16)
return c
}
// NGServer is a http server which push captured HTTPEvent to the front end
type NGServer struct {
addr string
staticFileDir string
connectedClient map[*websocket.Conn]*NGClient
connectedClientMutex *sync.Mutex
eventBuffer []interface{}
saveEvent bool
wg sync.WaitGroup
}
func (s *NGServer) websocketHandler(ws *websocket.Conn) {
c := NewNGClient(ws, s)
s.connectedClientMutex.Lock()
s.connectedClient[ws] = c
s.connectedClientMutex.Unlock()
go c.transmitEvents()
c.recvAndProcessCommand()
c.close()
s.connectedClientMutex.Lock()
delete(s.connectedClient, ws)
s.connectedClientMutex.Unlock()
}
// PushEvent dispatches the event received from ngnet to all clients connected with websocket.
func (s *NGServer) PushEvent(e interface{}) {
if s.saveEvent {
s.eventBuffer = append(s.eventBuffer, e)
}
s.connectedClientMutex.Lock()
for _, c := range s.connectedClient {
c.eventChan <- e
}
s.connectedClientMutex.Unlock()
}
// Wait waits for serving
func (s *NGServer) Wait() {
s.wg.Wait()
}
/*
If the flag '-s' is set and the browser sent a 'sync' command,
the NGServer will push all the http message buffered in eventBuffer to
the client.
*/
func (s *NGServer) sync(c *NGClient) {
for _, ev := range s.eventBuffer {
c.eventChan <- ev
}
}
/*
Handle static files (.html, .js, .css).
*/
func (s *NGServer) handleStaticFile(w http.ResponseWriter, r *http.Request) {
uri := r.RequestURI
if uri == "/" {
uri = "/index.html"
}
c, err := web.GetContent(uri)
if err != nil {
log.Println(r.RequestURI)
http.NotFound(w, r)
return
}
w.Write([]byte(c))
}
func (s *NGServer) listenAndServe() {
defer s.wg.Done()
err := http.ListenAndServe(s.addr, nil)
if err != nil {
log.Fatalln(err)
}
}
// Serve the web page
func (s *NGServer) Serve() {
http.Handle("/data", websocket.Handler(s.websocketHandler))
/*
If './client' directory exists, create a FileServer with it,
otherwise we use package client.
*/
_, err := os.Stat("client")
if err == nil {
fs := http.FileServer(http.Dir("client"))
http.Handle("/", fs)
} else {
http.HandleFunc("/", s.handleStaticFile)
}
s.wg.Add(1)
go s.listenAndServe()
}
// NewNGServer creates NGServer
func NewNGServer(addr string, saveEvent bool) *NGServer {
s := new(NGServer)
s.addr = addr
s.connectedClient = make(map[*websocket.Conn]*NGClient)
s.connectedClientMutex = &sync.Mutex{}
s.saveEvent = saveEvent
return s
}