/
tunnel.go
57 lines (52 loc) · 1.32 KB
/
tunnel.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
package livereload
import (
"encoding/json"
"regexp"
"github.com/gorilla/websocket"
)
var regexHandshake = regexp.MustCompile(`"command"\s*:\s*"hello"`)
/* ----------------------------------------------------------------------
* WebSocket Server Tunnel
* ----------------------------------------------------------------------*/
type tunnel struct {
socket *websocket.Conn
message chan []byte
}
// connect reads/writes message for livereload.js.
func (self *tunnel) connect() {
// ***********************
// WebSocket Tunnel#Write
// ***********************
go func() {
for message := range self.message {
if err := self.socket.WriteMessage(websocket.TextMessage, message); err != nil {
break
} else {
if regexHandshake.Find(message) != nil {
// Keep the tunnel opened after handshake(hello command).
Reload()
}
}
}
self.socket.Close()
}()
// ***********************
// WebSocket Tunnel#Read
// ***********************
for {
_, message, err := self.socket.ReadMessage()
if err != nil {
break
}
switch true {
case regexHandshake.Find(message) != nil:
var bytes, _ = json.Marshal(&hello{
Command: "hello",
Protocols: []string{"http://livereload.com/protocols/official-7"},
ServerName: "Rex#Livereload",
})
self.message <- bytes
}
}
self.socket.Close()
}