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
|
package main
import (
"crypto/tls"
"net/http"
"strings"
"sync"
)
const xForwardedProto = "X-Forwarded-Proto"
const xForwardedProtoHTTPS = "https"
type theApp struct {
domains domains
lock sync.RWMutex
}
func (a *theApp) domain(host string) *domain {
host = strings.ToLower(host)
a.lock.RLock()
defer a.lock.RUnlock()
domain, _ := a.domains[host]
return domain
}
func (a *theApp) ServeTLS(ch *tls.ClientHelloInfo) (*tls.Certificate, error) {
if ch.ServerName == "" {
return nil, nil
}
if domain := a.domain(ch.ServerName); domain != nil {
tls, _ := domain.ensureCertificate()
return tls, nil
}
return nil, nil
}
func (a *theApp) serveContent(ww http.ResponseWriter, r *http.Request, https bool) {
w := newLoggingResponseWriter(ww)
defer w.Log(r)
// Add auto redirect
if https && !*serverHTTP {
u := *r.URL
u.Scheme = "https"
u.Host = r.Host
u.User = nil
http.Redirect(&w, r, u.String(), 307)
return
}
domain := a.domain(r.Host)
if domain == nil {
http.NotFound(&w, r)
return
}
// Serve static file
domain.ServeHTTP(&w, r)
}
func (a *theApp) ServeHTTP(ww http.ResponseWriter, r *http.Request) {
https := r.TLS != nil
a.serveContent(ww, r, https)
}
func (a *theApp) ServeProxy(ww http.ResponseWriter, r *http.Request) {
forwardedProto := r.Header.Get(xForwardedProto)
https := forwardedProto == xForwardedProtoHTTPS
a.serveContent(ww, r, https)
}
func (a *theApp) UpdateDomains(domains domains) {
a.lock.Lock()
defer a.lock.Unlock()
a.domains = domains
}
|