/
reverseproxy.go
74 lines (62 loc) · 1.57 KB
/
reverseproxy.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
package main
import (
"bufio"
"encoding/json"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
)
const HOSTPORT = 80
type Host struct {
HostAddress string
TargetAddress string
Name string
}
func (h *Host) getTargetURL() *url.URL {
url, err := url.Parse("http://localhost:" + h.TargetAddress)
check(err)
return url
}
func (h *Host) getHostURL() *url.URL {
url, err := url.Parse(h.HostAddress)
check(err)
return url
}
type Config struct {
Hosts []Host
}
type HandlerFunc func(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request)
func check(e error) {
if e != nil {
panic(e)
}
}
func addReversePortProxy(hostAddress *url.URL, targetAddress *url.URL, httpHandler HandlerFunc) {
proxy := httputil.NewSingleHostReverseProxy(targetAddress)
http.HandleFunc(hostAddress.String(), httpHandler(proxy))
log.Printf("Redirecting %s to %s on port %s\n", hostAddress.String(), targetAddress.String(), strconv.Itoa(HOSTPORT))
}
func getConfig(configFile string) Config {
f, err := os.Open(configFile)
check(err)
cfg := Config{}
json.NewDecoder(bufio.NewReader(f)).Decode(&cfg)
return cfg
}
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
p.ServeHTTP(w, r)
}
}
func main() {
cfg := getConfig("proxyconfig.json")
for _, host := range cfg.Hosts {
addReversePortProxy(host.getHostURL(), host.getTargetURL(), handler)
}
err := http.ListenAndServe(":"+strconv.Itoa(HOSTPORT), nil)
check(err)
}