-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
executable file
·98 lines (84 loc) · 1.9 KB
/
proxy.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
package main
import (
"html/template"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
var tmpl, _ = template.New("502").Parse(error_502)
type Proxy struct {
}
func (proxy *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id, port, err := net.SplitHostPort(r.Header.Get("docker"))
if err != nil {
renderError(w, 502)
return
}
container, err := inspectCachedContainer(id)
if err != nil || container == nil {
renderError(w, 503)
return
}
scheme := "http://"
if r.URL.Scheme != "" {
scheme = r.URL.Scheme
}
backend, err := url.Parse(scheme + container.NetworkSettings.IPAddress + ":" + port)
if err != nil {
renderError(w, 503)
return
}
// Reverse proxy the request.
// (Need special code for websockets, courtesy of bradfitz)
if r.Header.Get("Upgrade") == "websocket" {
proxyWebsocket(w, r, backend.Host)
} else {
p := httputil.NewSingleHostReverseProxy(backend)
p.ServeHTTP(w, r)
}
}
// proxyWebsocket copies data between websocket client and server until one side
// closes the connection. (ReverseProxy doesn't work with websocket requests.)
func proxyWebsocket(w http.ResponseWriter, r *http.Request, host string) {
d, err := net.Dial("tcp", host)
if err != nil {
http.Error(w, "Error contacting backend server.", 500)
return
}
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Not a hijacker?", 500)
return
}
nc, _, err := hj.Hijack()
if err != nil {
return
}
defer nc.Close()
defer d.Close()
err = r.Write(d)
if err != nil {
return
}
errc := make(chan error, 2)
cp := func(dst io.Writer, src io.Reader) {
_, err := io.Copy(dst, src)
errc <- err
}
go cp(d, nc)
go cp(nc, d)
<-errc
}
func removePort(s string) string {
return s[:strings.LastIndex(s, ":")]
}
func getHost(s string) string {
return s[:strings.Index(s, ".")]
}
func renderError(w http.ResponseWriter, code int) {
w.WriteHeader(code)
tmpl.Execute(w, nil)
}