forked from fabiolb/fabio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws.go
42 lines (36 loc) · 964 Bytes
/
ws.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
package proxy
import (
"io"
"log"
"net/http"
"net/url"
"golang.org/x/net/websocket"
)
// newWSProxy returns a websocket handler which forwards
// messages from an incoming WS connection to an outgoing
// WS connection. It builds upon the golang.org/x/net/websocket
// library for both incoming and outgoing connections.
func newWSProxy(t *url.URL) http.Handler {
return websocket.Handler(func(in *websocket.Conn) {
defer in.Close()
r := in.Request()
targetURL := "ws://" + t.Host + r.RequestURI
out, err := websocket.Dial(targetURL, "", r.Header.Get("Origin"))
if err != nil {
log.Printf("[INFO] WS error for %s. %s", r.URL, err)
return
}
defer out.Close()
errc := make(chan error, 2)
cp := func(dst io.Writer, src io.Reader) {
_, err := io.Copy(dst, src)
errc <- err
}
go cp(out, in)
go cp(in, out)
err = <-errc
if err != nil && err != io.EOF {
log.Printf("[INFO] WS error for %s. %s", r.URL, err)
}
})
}