-
Notifications
You must be signed in to change notification settings - Fork 1
/
vhost.go
188 lines (159 loc) · 4.05 KB
/
vhost.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package vproxy
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/gammazero/deque"
"github.com/txn2/txeh"
)
// Vhost represents a single backend service
type Vhost struct {
Host string // virtual host name
ServiceHost string // service host or IP
Port int // service port
Handler http.Handler
Cert string // TLS Certificate
Key string // TLS Private Key
logRing *deque.Deque
logChan LogListener
listeners []LogListener
}
type LogListener chan string
// VhostMux is an http.Handler whose ServeHTTP forwards the request to
// backend Servers according to the incoming request URL
type VhostMux struct {
Servers map[string]*Vhost
}
func (v *VhostMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
originalURL := r.Host + r.URL.Path
host := getHostName(r.Host)
vhost := v.Servers[host]
if vhost == nil {
log.Printf("Host Not Found: `%s`", host)
w.WriteHeader(404)
fmt.Fprintln(w, "host not found:", host)
return
}
defer func() {
if val := recover(); val != nil {
log.Printf("Error proxying request `%s` to `%s`: %v", originalURL, r.URL, val)
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintf(w, "Error proxying request `%s` to `%s`: %v", originalURL, r.URL, val)
}
}()
// handle it
vhost.Handler.ServeHTTP(w, r)
}
// DumpServers to the given writer
func (v *VhostMux) DumpServers(w io.Writer) {
switch c := len(v.Servers); c {
case 0:
fmt.Fprintln(w, "0 vhosts")
case 1:
fmt.Fprintln(w, "1 vhost:")
default:
fmt.Fprintf(w, "%d vhosts:\n", c)
}
for _, v := range v.Servers {
fmt.Fprintf(w, "%s -> %s:%d\n", v.Host, v.ServiceHost, v.Port)
}
}
// CreateVhostMux config, optionally initialized with a list of bindings
func CreateVhostMux(bindings []string, useTLS bool) *VhostMux {
servers := make(map[string]*Vhost)
for _, binding := range bindings {
if binding != "" {
vhost, err := CreateVhost(binding, useTLS)
if err != nil {
// on startup, bail immediately
log.Fatal(err)
}
servers[vhost.Host] = vhost
}
}
return &VhostMux{Servers: servers}
}
// CreateVhost for the host:port pair, optionally with a TLS cert
func CreateVhost(input string, useTLS bool) (*Vhost, error) {
s := strings.Split(input, ":")
if len(s) < 2 {
// invalid binding
return nil, fmt.Errorf("error: invalid binding '%s'", input)
}
hostname := s[0]
targetPort, err := strconv.Atoi(s[1])
if err != nil {
return nil, fmt.Errorf("failed to parse target port: %s", err)
}
targetHost := "127.0.0.1"
targetURL := url.URL{Scheme: "http", Host: fmt.Sprintf("%s:%d", targetHost, targetPort)}
proxy := CreateProxy(targetURL, hostname)
vhost := &Vhost{
Host: hostname, ServiceHost: targetHost, Port: targetPort, Handler: proxy,
logRing: deque.New(10, 16),
logChan: make(LogListener, 10),
}
go vhost.populateLogBuffer()
if useTLS {
vhost.Cert, vhost.Key, err = MakeCert(hostname)
if err != nil {
return nil, fmt.Errorf("failed to generate cert for host %s: %s", hostname, err)
}
}
return vhost, nil
}
func (v *Vhost) NewLogListener() LogListener {
logChan := make(LogListener, 100)
v.listeners = append(v.listeners, logChan)
return logChan
}
func (v *Vhost) RemoveLogListener(logChan LogListener) {
index := 0
for _, i := range v.listeners {
if i != logChan {
v.listeners[index] = i
index++
}
}
v.listeners = v.listeners[:index]
}
func (v *Vhost) BufferAsString() string {
if v.logRing.Len() == 0 {
return ""
}
buff := ""
for i := 0; i < v.logRing.Len(); i++ {
s := v.logRing.At(i).(string)
if s != "" {
buff += s + "\n"
}
}
return buff
}
func (v *Vhost) Close() {
close(v.logChan)
v.logRing.Clear()
}
func (v *Vhost) populateLogBuffer() {
for line := range v.logChan {
if v.logRing.Len() < 10 {
v.logRing.PushBack(line)
} else {
v.logRing.Rotate(1)
v.logRing.Set(9, line)
}
}
}
// Map given host to 127.0.0.1 in system hosts file (usually /etc/hosts)
func addToHosts(host string) error {
hosts, err := txeh.NewHostsDefault()
if err != nil {
return err
}
hosts.AddHost("127.0.0.1", host)
return hosts.Save()
}