-
Notifications
You must be signed in to change notification settings - Fork 0
/
webs.go
199 lines (182 loc) · 4.12 KB
/
webs.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
189
190
191
192
193
194
195
196
197
198
199
package webs
import (
"context"
"crypto/tls"
"net/http"
"strings"
"time"
"github.com/msw-x/moon/app"
"github.com/msw-x/moon/secret"
"github.com/msw-x/moon/ufmt"
"github.com/msw-x/moon/ulog"
"github.com/msw-x/moon/usync"
"golang.org/x/crypto/acme/autocert"
)
type Server struct {
log *ulog.Log
s *http.Server
do *usync.Do
timeout Timeout
certFile string
keyFile string
domains []string
tlsman *autocert.Manager
xRemoteAddress string
logRequests bool
logErrors *ulog.Level
}
func New() *Server {
return &Server{
timeout: Timeout{
Write: 15 * time.Second,
Read: 15 * time.Second,
Idle: 60 * time.Second,
Close: 5 * time.Second,
},
}
}
func (o *Server) WithSecret(certFile, keyFile string) *Server {
o.certFile = certFile
o.keyFile = keyFile
return o
}
func (o *Server) WithSecretDir(dir string) *Server {
o.certFile, o.keyFile = secret.FileNames(dir)
return o
}
func (o *Server) WithAutoSecret(dir string, domains ...string) *Server {
o.certFile = ""
o.keyFile = ""
o.domains = splitDomains(domains[:])
if len(o.domains) > 0 && o.domains[0] != "" {
o.tlsman = &autocert.Manager{
Cache: autocert.DirCache(dir),
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(o.domains...),
}
} else {
o.WithSecretDir(dir)
}
return o
}
func (o *Server) WithLogRequests(use bool) *Server {
o.logRequests = use
return o
}
func (o *Server) WithLogErrors(use bool) *Server {
if use {
if o.logErrors == nil {
o.WithLogErrorsLevel(ulog.LevelError)
}
} else {
o.logErrors = nil
}
return o
}
func (o *Server) WithLogErrorsLevel(level ulog.Level) *Server {
o.logErrors = &level
return o
}
func (o *Server) WithXRemoteAddress(s string) *Server {
o.xRemoteAddress = s
return o
}
func (o *Server) WithTimeout(timeout Timeout) *Server {
o.timeout = timeout
return o
}
func (o *Server) Run(addr string, handler http.Handler) {
if addr == "" {
return
}
name := "http"
if o.IsTls() {
name = "https"
if o.tlsman == nil {
secret.Ensure(o.certFile, o.keyFile)
}
}
o.log = ulog.New(name).WithID(addr)
if o.IsTls() {
if o.tlsman == nil {
o.log.Info("cert:", o.certFile)
o.log.Info("key:", o.keyFile)
} else {
o.log.Info("domains:", ufmt.JoinSlice(o.domains))
}
}
if o.logRequests {
handler = o.LogRequest(handler)
}
o.s = &http.Server{
Addr: addr,
Handler: handler,
WriteTimeout: o.timeout.Write,
ReadTimeout: o.timeout.Read,
IdleTimeout: o.timeout.Idle,
ErrorLog: ulog.StdBridge(func(m string) {
if o.logErrors != nil {
level := *o.logErrors
o.log.Print(level, m)
}
}),
}
if o.tlsman != nil {
o.s.TLSConfig = o.tlsman.TLSConfig()
o.s.TLSConfig.GetCertificate = func(hello *tls.ClientHelloInfo) (cert *tls.Certificate, err error) {
timeout := 10 * time.Second
timer := time.AfterFunc(timeout, func() {
o.log.Warning("getting the certificate takes more than", timeout)
})
defer timer.Stop()
return o.tlsman.GetCertificate(hello)
}
}
o.do = usync.NewDo()
app.Go(func() {
defer func() {
o.log.Info("stopped")
o.do.Notify()
}()
o.log.Info("listen")
var err error
if o.IsTls() {
err = o.s.ListenAndServeTLS(o.certFile, o.keyFile)
} else {
err = o.s.ListenAndServe()
}
if o.s != nil && err != nil {
o.log.Error(err)
}
})
}
func (o *Server) Shutdown() {
if o.s != nil {
ctx, cancel := context.WithTimeout(context.Background(), o.timeout.Close)
defer cancel()
o.log.Info("shutdown")
s := o.s
o.s = nil
s.Shutdown(ctx)
o.do.Stop()
o.log.Info("shutdown completed")
}
}
func (o *Server) IsTls() bool {
return o.certFile != "" && o.keyFile != "" || o.tlsman != nil
}
func (o *Server) LogRequest(mux http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := RequestNameX(r, o.xRemoteAddress)
o.log.Debug(name)
tm := time.Now()
mux.ServeHTTP(w, r)
o.log.Debug(name, time.Since(tm).Truncate(time.Millisecond))
})
}
func splitDomains(l []string) (r []string) {
for _, s := range l {
r = append(r, strings.Split(s, " ")...)
}
return
}