/
main.go
117 lines (96 loc) · 2.36 KB
/
main.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"os"
"github.com/benschw/dns-clb-go/clb"
)
func dnsLb() (c clb.LoadBalancer) {
dnsHost := os.Getenv("DNS_HOST")
if dnsHost != "" {
dnsPort := os.Getenv("DNS_PORT")
if dnsPort == "" {
dnsPort = "53"
}
c = clb.NewClb(dnsHost, dnsPort, clb.RoundRobin)
} else {
c = clb.NewDefaultClb(clb.RoundRobin)
}
return c
}
func getServiceUrl(s string) *url.URL {
addr, err := dnsLb().GetAddress(s + ".service.consul")
if err != nil {
fmt.Fprintf(os.Stderr, "[WARNING] service: %s isnt registered yet ...", s)
return nil
}
url, err := url.Parse("http://" + addr.String())
if err != nil {
fmt.Fprintf(os.Stderr, "[WARNING] cloudn't parse address: %s", addr.String())
return nil
}
return url
}
func port() string {
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
if port[0] != ':' {
port = ":" + port
}
fmt.Println("[INFO] listening on:", port)
return port
}
type ServiceProxyHandler struct {
ServiceName string
Patt string
ServiceURL *url.URL
ProxyHandler http.Handler
}
func (h *ServiceProxyHandler) refreshURL() {
u := getServiceUrl(h.ServiceName)
if u != h.ServiceURL {
h.ServiceURL = u
p := httputil.NewSingleHostReverseProxy(u)
h.ProxyHandler = http.StripPrefix(h.Patt, p)
fmt.Printf("[DEBUG] proxy created: pattern: %s url: %s", h.Patt, h.ServiceURL.String())
}
}
func (h *ServiceProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Println("[DEBUG] ServeHTTP()... ")
h.refreshURL()
if h.ServiceURL != nil {
if os.Getenv("DEBUG") != "" {
fmt.Printf("[DEBUG] PATT: %-10s REQ-URL:%s -> %s \n", h.Patt, r.URL.String(), h.ServiceURL.String())
}
r.Header.Set("x-proxy-prefix", h.Patt)
h.ProxyHandler.ServeHTTP(w, r)
} else {
fmt.Fprintf(os.Stderr, "[WARNING] ServiceURL is unknown ...\n")
}
}
func NewServiceProxyHandler(service string, patt string) *ServiceProxyHandler {
fmt.Println("[INFO] new proxy", patt, "->", service)
h := &ServiceProxyHandler{
ServiceName: service,
Patt: patt,
}
return h
}
func main() {
for _, s := range []struct {
service string
patt string
}{
{"cloudbreak", "/cloudbreak/"},
{"identity", "/identity/"},
{"sultans", "/sultans/"},
{"uluwatu", "/"},
} {
http.Handle(s.patt, NewServiceProxyHandler(s.service, s.patt))
}
http.ListenAndServe(port(), nil)
}