-
Notifications
You must be signed in to change notification settings - Fork 4
/
wspipe.go
65 lines (58 loc) · 1.51 KB
/
wspipe.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
package wspipe
import (
"net/http"
"sync"
"github.com/gorilla/websocket"
)
type WSPipe struct {
upgrader websocket.Upgrader
pairs sync.Map
version string
token string
}
func (self *WSPipe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !websocket.IsWebSocketUpgrade(r) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
} else if self.token != r.URL.Query().Get("token") {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
} else if conn, err := self.upgrader.Upgrade(w, r, nil); err == nil {
defer conn.Close()
path := r.URL.Path
pair := self.getPair(path)
if right, err := pair.Join(conn); err == nil {
defer self.deletePair(path)
defer pair.Close()
if right {
wscopy(r.Context(), pair.Left, conn)
} else {
ctx := r.Context()
select {
case <-ctx.Done():
case <-pair.Ready():
wscopy(ctx, pair.Right, conn)
}
}
}
}
}
func (self *WSPipe) getPair(path string) *wspair {
pair := &wspair{ready: make(chan struct{})}
if actual, loaded := self.pairs.LoadOrStore(path, pair); loaded {
close(pair.ready)
return actual.(*wspair)
} else {
return actual.(*wspair)
}
}
func (self *WSPipe) deletePair(path string) { self.pairs.Delete(path) }
func Build(ver, token string) (http.Handler, error) {
return &WSPipe{
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(*http.Request) bool { return true },
},
version: ver,
token: token,
}, nil
}