forked from fabiolb/fabio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
raw.go
58 lines (51 loc) · 1.4 KB
/
raw.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
package proxy
import (
"io"
"log"
"net"
"net/http"
"net/url"
)
// newRawProxy returns an HTTP handler which forwards data between
// an incoming and outgoing TCP connection including the original request.
// This handler establishes a new outgoing connection per request.
func newRawProxy(t *url.URL) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "not a hijacker", http.StatusInternalServerError)
return
}
in, _, err := hj.Hijack()
if err != nil {
log.Printf("[ERROR] Hijack error for %s. %s", r.URL, err)
http.Error(w, "hijack error", http.StatusInternalServerError)
return
}
defer in.Close()
out, err := net.Dial("tcp", t.Host)
if err != nil {
log.Printf("[ERROR] WS error for %s. %s", r.URL, err)
http.Error(w, "error contacting backend server", http.StatusInternalServerError)
return
}
defer out.Close()
err = r.Write(out)
if err != nil {
log.Printf("[ERROR] Error copying request for %s. %s", r.URL, err)
http.Error(w, "error copying request", http.StatusInternalServerError)
return
}
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)
}
})
}