-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
131 lines (104 loc) · 2.5 KB
/
config.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/yaml.v2"
)
type config struct {
Email string
CacheFile string `yaml:"cacheFile"`
UseHSTS bool `yaml:"useHSTS"`
Endpoints []endpoint
m map[string][]endpoint
}
var (
routeHit = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http_proxy_route_hit",
Help: "A route was found for a requested host",
}, []string{"host"})
routeMiss = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http_proxy_route_miss",
Help: "A route was requested that was not present.",
}, []string{"host"})
)
func init() {
prometheus.MustRegister(routeMiss, routeHit)
}
type endpoint struct {
Hostname, Backend, Directory string
Q map[string]string
rp http.Handler
}
func (cfg *config) rm(r *http.Request) http.Handler {
if cfgs, ok := cfg.m[r.Host]; ok {
findBackend:
// Check the configs for this host, validate all other selectors match
for _, c := range cfgs {
for k, v := range c.Q {
if r.URL.Query().Get(k) != v {
continue findBackend
}
}
routeHit.With(prometheus.Labels{"host": r.Host}).Inc()
return c.rp
}
}
routeMiss.With(prometheus.Labels{"host": r.Host}).Inc()
if c, ok := cfg.m["*"]; ok && len(c) > 0 {
return c[0].rp
}
return nil
}
func (cfg *config) init() error {
cfg.m = map[string][]endpoint{}
for _, c := range cfg.Endpoints {
switch {
case c.Backend != "":
log.Printf("Generating config for %s", c.Hostname)
url, err := url.ParseRequestURI(c.Backend)
if err != nil {
return err
}
c.rp = httputil.NewSingleHostReverseProxy(url)
if _, ok := cfg.m[c.Hostname]; !ok {
cfg.m[c.Hostname] = []endpoint{}
}
case c.Directory != "":
c.rp = http.FileServer(http.Dir(c.Directory))
}
cfg.m[c.Hostname] = append(cfg.m[c.Hostname], c)
}
return nil
}
func (cfg *config) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Println(r.Host, r.URL, r.RemoteAddr)
handler := cfg.rm(r)
if handler != nil {
if cfg.UseHSTS {
w.Header().Set("Strict-Transport-Security", "max-age=10886400; includeSubDomains; preload")
}
handler.ServeHTTP(w, r)
return
}
http.Error(w, "Not Found", 404)
}
func readConfig(fname string) (*config, error) {
bs, err := ioutil.ReadFile(fname)
if err != nil {
return nil, err
}
var cfg config
err = yaml.Unmarshal(bs, &cfg)
if err != nil {
return nil, err
}
err = cfg.init()
if err != nil {
return nil, err
}
return &cfg, nil
}