forked from calavera/active-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
82 lines (66 loc) · 1.56 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
package main
import (
"fmt"
"github.com/daaku/go.grace/gracehttp"
"io"
"log"
"net/http"
"strings"
)
type application struct {
Name string
Port string
Test string
}
type proxy struct {
apps map[string]*application
Address string
Transport *http.Transport
}
func NewProxy(address string) *proxy {
p := &proxy{Address: address}
p.Init()
return p
}
func (p *proxy) Init() {
p.apps = make(map[string]*application)
}
func (p *proxy) Start() {
mux := http.NewServeMux()
mux.Handle("/", p)
p.Transport = &http.Transport{DisableKeepAlives: false, DisableCompression: false}
log.Printf("Starting proxy at %s\n", p.Address)
log.Fatal(gracehttp.Serve(&http.Server{Handler: mux, Addr: p.Address}))
}
func (p *proxy) Route(app *application) {
p.apps[app.Name] = app
log.Printf("Routing application `%s` to `%s`", app.Name, app.Port)
}
func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := strings.Split(r.URL.Path, "/")[1]
app, ok := p.apps[path]
if ok {
r.URL.Scheme = "http"
r.URL.Host = "localhost:" + app.Port
resp, err := p.Transport.RoundTrip(r)
if err != nil {
p.responseError(err, w)
} else {
for k, v := range resp.Header {
for _, vv := range v {
w.Header().Add(k, vv)
}
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
resp.Body.Close()
}
} else {
p.responseError(fmt.Errorf("Not found"), w)
}
}
func (p *proxy) responseError(err error, w http.ResponseWriter) {
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintf(w, "Error: %v", err)
log.Printf("Error: %v", err)
}