This repository was archived by the owner on Oct 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebserver.go
More file actions
322 lines (258 loc) · 7.75 KB
/
Copy pathwebserver.go
File metadata and controls
322 lines (258 loc) · 7.75 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package main
import (
"context"
"embed"
"errors"
"fmt"
"io/fs"
"log/slog"
"net"
"net/http"
"path/filepath"
"time"
"github.com/a-h/templ"
"golang.org/x/sync/errgroup"
)
const (
httpShutdownPreStopDelaySeconds = 0
httpShutdownTimeoutSeconds = 0
defaultBackgroundTimeoutSeconds = 2
)
//go:embed assets
var fsAssets embed.FS
type responseRecorder struct {
w http.ResponseWriter
status int
}
func (rr *responseRecorder) WriteHeader(status int) {
rr.status = status
rr.w.WriteHeader(status)
}
func (rr *responseRecorder) Header() http.Header {
return rr.w.Header()
}
func (rr *responseRecorder) Write(b []byte) (int, error) {
return rr.w.Write(b)
}
type headerWriter struct {
headers map[string]string
w http.ResponseWriter
wroteHeader bool
}
func newHeaderWriter(local bool, w http.ResponseWriter) *headerWriter {
headers := map[string]string{
"Content-Security-Policy:": "default-src 'self'", // https://report-uri.com/home/generate
"X-XSS-Protection": "1; mode=block",
"X-Frame-Options": "sameorigin",
"X-Content-Type-Options": "nosniff",
"X-Permitted-Cross-Domain-Policies": "none",
"Referrer-Policy": "no-referrer-when-downgrade",
}
// TODO: local only
if false {
headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains; preload"
}
return &headerWriter{
headers: headers,
w: w,
wroteHeader: false,
}
}
func (hr *headerWriter) WriteHeader(status int) {
// Other handlers did a w.WriteHeader(status).
if !hr.wroteHeader {
for k, v := range hr.headers {
hr.w.Header().Set(k, v)
}
hr.wroteHeader = true
}
hr.w.WriteHeader(status)
}
func (hr *headerWriter) Header() http.Header {
return hr.w.Header()
}
func (hr *headerWriter) Write(b []byte) (int, error) {
// Other handlers didn't do a WriteHeader(status).
if !hr.wroteHeader {
for k, v := range hr.headers {
hr.w.Header().Set(k, v)
}
hr.wroteHeader = true
}
return hr.w.Write(b)
}
type WebServer struct {
mux *http.ServeMux
srv *http.Server
logger *slog.Logger
subber *Subber
assets http.FileSystem
}
func NewWebServer(logger *slog.Logger, listenAddr string, subber *Subber) (*WebServer, error) {
fsys, err := fs.Sub(fsAssets, "assets")
if err != nil {
return nil, err
}
mux := http.NewServeMux()
hs := &http.Server{
Addr: listenAddr,
Handler: mux,
DisableGeneralOptionsHandler: false,
ReadTimeout: 10 * time.Second,
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 10 * time.Second,
MaxHeaderBytes: 10 >> 10,
TLSNextProto: nil,
ConnState: nil,
// ErrorLog: &log.Logger{},
// BaseContext: func(net.Listener) context.Context {
// },
// ConnContext: func(ctx context.Context, c net.Conn) context.Context {
// },
}
ws := &WebServer{
mux: mux,
srv: hs,
logger: logger,
subber: subber,
assets: http.FS(fsys),
}
// attach routes to WebServer. This is a awkward compared to defining during
// struct construction like `mc` but required in order for routes to have
// access to private fields defined on the WebServer struct, such as loggers,
// tracing, etc.
ws.setRoutes()
return ws, nil
}
// Run starts the HTTP Server application and gracefully shuts down when the
// provided context is marked done.
func (ws *WebServer) Run(ctx context.Context) error {
ln, err := net.Listen("tcp", ws.srv.Addr)
if err != nil {
return err
}
// TODO: replace `[::]:8081` with http://localhost:8081 or something clickable.
ws.logger.Info(fmt.Sprintf("listening on: %s", ln.Addr().String()))
var group errgroup.Group
group.Go(func() error {
<-ctx.Done()
// before shutting down the HTTP server wait for any HTTP requests that are
// in transit on the network. Common in Kubernetes and other distributed
// systems.
time.Sleep(httpShutdownPreStopDelaySeconds * time.Second)
// give active connections time to complete or disconnect before closing.
drainTimeoutCtx, cancel := context.WithTimeout(ctx, httpShutdownTimeoutSeconds*time.Second)
defer cancel()
return ws.srv.Shutdown(drainTimeoutCtx)
})
group.Go(func() error {
err := ws.srv.Serve(ln)
// http.ErrServerClosed is expected at shutdown.
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
})
return group.Wait()
}
func (ws *WebServer) respondError(status int, err error, w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(status)
ws.logger.Error("respondError()", slog.String("error", err.Error()))
}
func (ws *WebServer) renderTemplate(status int, t templ.Component, w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
if err := t.Render(r.Context(), w); err != nil {
ws.logger.Error("t.Render()", slog.String("error", err.Error()))
w.WriteHeader(http.StatusInternalServerError)
}
}
func (ws *WebServer) middlewareChain(next http.Handler) http.HandlerFunc {
return ws.securityMiddleware(
ws.loggingMiddleware(
ws.corsMiddleware(
func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
},
)))
}
// corsMiddleware responds to OPTION requests and injects CORS headers when required.
// See: https://bunrouter.uptrace.dev/guide/golang-cors.html
func (ws *WebServer) corsMiddleware(next func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
next(w, r)
return
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,HEAD")
w.Header().Set("Access-Control-Allow-Headers", "authorization,content-type,content-length")
w.Header().Set("Access-Control-Max-Age", "86400")
w.WriteHeader(http.StatusNoContent)
return
}
next(w, r)
}
}
func (ws *WebServer) securityMiddleware(next func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// TODO, get local from env
hr := newHeaderWriter(true, w)
next(hr, r)
// Other handlers didn't WriteHeader(status) or Write(b).
if !hr.wroteHeader {
for k, v := range hr.headers {
hr.w.Header().Set(k, v)
}
hr.wroteHeader = true
}
}
}
func (ws *WebServer) loggingMiddleware(next func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rr := &responseRecorder{
w: w,
status: http.StatusOK, // default, handlers will override if need.
}
start := time.Now()
next(rr, r)
ws.logger.WithGroup("request").LogAttrs(
r.Context(), slog.LevelInfo.Level(), "http request",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", rr.status),
slog.Int64("duration_us", time.Since(start).Microseconds()),
)
}
}
// HandleStaticFiles is a HTTP handler for static files available in the
// embedded filesystem set in NewWebServer().
func (ws *WebServer) HandleStaticFiles() http.HandlerFunc {
fs := http.FileServer(ws.assets)
return func(w http.ResponseWriter, r *http.Request) {
path := filepath.Clean(r.URL.Redacted())
f, err := ws.assets.Open(path)
if err != nil {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
stat, err := f.Stat()
if err != nil {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
if stat.IsDir() {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
closeErr := f.Close()
if closeErr != nil {
http.NotFoundHandler().ServeHTTP(w, r)
return
}
fs.ServeHTTP(w, r)
}
}