-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
111 lines (97 loc) · 2.13 KB
/
run.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
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
package sock
import (
"mime"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gopherjs/gopherjs/js"
"github.com/gorilla/websocket"
)
func run() {
if IsClient {
runClient()
} else {
runServer()
}
}
func runClient() {
wsOrWSS := "wss://"
if !Secure {
wsOrWSS = "ws://"
}
wsync.Lock()
defer wsync.Unlock()
ws = js.Global.Get("WebSocket").New(wsOrWSS + Addr + Route)
ws.Set("binaryType", "arraybuffer")
ws.Set("onopen", func() {
ws.Set("onmessage", func(e *js.Object) {
go func(pkt []byte) {
err := read(pkt)
if err != nil {
wsync.Lock()
ws.Call("close")
wsync.Unlock()
}
}(js.Global.Get("Uint8Array").New(e.Get("data")).Interface().([]byte))
})
})
ws.Set("onclose", func() { go runClient() })
}
func runServer() {
if len(Root) > 0 {
if _, err := os.Stat(Root); os.IsNotExist(err) {
panic("root folder missing")
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// var p []string
ext := filepath.Ext(r.URL.Path)
if ext == ".gz" {
// p = append(p, "Content-Encoding: gzip")
w.Header().Add("Content-Encoding", "gzip")
}
idx := strings.LastIndex(r.URL.Path, ext)
if idx != -1 {
ext = filepath.Ext(r.URL.Path[:idx])
if t := mime.TypeByExtension(ext); len(t) > 0 {
// p = append(p, "Content-Type: "+t)
w.Header().Add("Content-Type", t)
}
}
http.ServeFile(w, r, Root+r.URL.Path)
// println(strings.Join(p, ", "))
})
}
up := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
http.HandleFunc(Route, func(w http.ResponseWriter, r *http.Request) {
conn, err := up.Upgrade(w, r, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
connl.Lock()
if len(conns) == 0 {
reboot.Unlock()
}
conns[conn] = true
connl.Unlock()
defer func() {
connl.Lock()
conn.Close()
delete(conns, conn)
if len(conns) == 0 {
reboot.Lock()
}
connl.Unlock()
}()
for {
mt, pkt, err := conn.ReadMessage()
if err != nil || mt != websocket.BinaryMessage || read(pkt) != nil {
return
}
}
})
go http.ListenAndServe(Addr, nil)
}