-
Notifications
You must be signed in to change notification settings - Fork 56
/
server.go
90 lines (70 loc) · 1.59 KB
/
server.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
package goVirtualHost
import (
"crypto/tls"
"net/http"
)
func newServer(useTLS bool) *server {
server := &server{
useTLS: useTLS,
vhosts: vhosts{},
defaultVhost: nil,
httpServer: &http.Server{},
}
return server
}
func (server *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var vhost *vhost
hostname := extractHostName(r.Host)
for _, vh := range server.vhosts {
if vh.matchHostName(hostname) {
vhost = vh
break
}
}
if vhost == nil {
vhost = server.defaultVhost
}
vhost.handler.ServeHTTP(w, r)
}
func (server *server) updateDefaultVhost() {
for _, vh := range server.vhosts {
if len(vh.hostNames) == 0 {
server.defaultVhost = vh
break
}
}
if server.defaultVhost == nil {
server.defaultVhost = server.vhosts[0]
}
}
func (server *server) updateHttpServerTLSConfig() {
var tlsConfig *tls.Config
if server.useTLS {
certs := []tls.Certificate{}
for _, vhost := range server.vhosts {
certs = append(certs, *vhost.cert)
}
tlsConfig = &tls.Config{
Certificates: certs,
}
tlsConfig.BuildNameToCertificate()
}
server.httpServer.TLSConfig = tlsConfig
}
func (server *server) updateHttpServerHandler() {
if len(server.vhosts) == 1 {
server.httpServer.Handler = server.defaultVhost.handler
return
}
server.httpServer.Handler = server
}
func (server *server) open(listener *listener) error {
if server.useTLS {
return server.httpServer.ServeTLS(listener.netListener, "", "")
} else {
return server.httpServer.Serve(listener.netListener)
}
}
func (server *server) close() error {
return server.httpServer.Close()
}