-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathproxy.go
96 lines (77 loc) · 2.48 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
package main
import (
"fmt"
"github.com/golang/glog"
"net/http"
"strings"
)
type domainResolver interface {
resolve(domain string) (http.Handler, error)
init()
}
type proxy struct {
config *Config
domainResolver domainResolver
}
func NewProxy(c *Config, resolver domainResolver) *proxy {
return &proxy{c, resolver}
}
type proxyHandler func(http.ResponseWriter, *http.Request) (*Config, error)
func (ph proxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
http.Error(w, "An error occured serving request", 500)
glog.Errorf("Recovered from error : %s", r)
}
}()
if c, err := ph(w, r); err != nil {
ph.OnError(w, r, err, c)
}
}
func (ph proxyHandler) OnError(w http.ResponseWriter, r *http.Request, error error, c *Config) {
if stError, ok := error.(StatusError); ok {
sp := &StatusPage{c, stError}
// Check if status is passivated -> setting expected state = started
if sp.error.computedStatus == PASSIVATED_STATUS {
reactivate(sp, c)
}
sp.serve(w, r)
} else {
sp := &StatusPage{c, StatusError{"notfound", nil}}
sp.serve(w, r)
}
}
func (p *proxy) start() {
glog.Infof("Listening on port %d", p.config.port)
http.Handle("/__static__/", http.FileServer(http.Dir(p.config.templateDir)))
http.Handle("/", proxyHandler(p.proxy))
glog.Fatalf("%s", http.ListenAndServe(fmt.Sprintf(":%d", p.config.port), nil))
}
func (p *proxy) proxy(w http.ResponseWriter, r *http.Request) (*Config, error) {
if p.config.forceFwSsl && "https" != r.Header.Get("x-forwarded-proto") {
http.Redirect(w, r, fmt.Sprintf("https://%s%s", hostnameOf(r.Host), r.URL.String()), http.StatusMovedPermanently)
return p.config, nil
}
host := hostnameOf(r.Host)
if server, err := p.domainResolver.resolve(host); err != nil {
return p.config, err
} else {
server.ServeHTTP(w, r)
return p.config, nil
}
}
func hostnameOf(host string) string {
hostname := strings.Split(host, ":")[0]
if len(hostname) > 4 && hostname[0:4] == "www." {
hostname = hostname[4:]
}
return hostname
}
func reactivate(sp *StatusPage, c *Config) {
client, _ := c.getEtcdClient()
_, error := client.Set(c.servicePrefix+"/"+sp.error.status.service.name+"/"+sp.error.status.service.index+"/status/expected", STARTED_STATUS, 0)
if error != nil {
glog.Errorf("Fail: setting expected state = 'started' for instance %s. Error:%s", sp.error.status.service.name, error)
}
glog.Infof("Instance %s is ready for re-activation", sp.error.status.service.name)
}