-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
71 lines (60 loc) · 1.63 KB
/
http.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
package recovery
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
)
type StackPrintOption string
const (
StackPrintLines StackPrintOption = "full"
StackPrintStructured StackPrintOption = "structured"
StackPrintNone StackPrintOption = "none"
)
type SlogHandlerOpts struct {
StackPrint StackPrintOption
}
func SlogHandler(opts SlogHandlerOpts) func(context.Context, error) {
return func(ctx context.Context, err error) {
switch opts.StackPrint {
case StackPrintStructured:
slog.ErrorContext(ctx, fmt.Sprintf("%v", err), "full", fmt.Sprintf("%+v", err))
case StackPrintLines:
slog.ErrorContext(ctx, fmt.Sprintf("%+v", err))
case StackPrintNone:
slog.ErrorContext(ctx, fmt.Sprintf("%v", err))
default:
slog.ErrorContext(ctx, fmt.Sprintf("%v", err))
}
}
}
type MiddlewareOpts struct {
ErrorHandler func(context.Context, error)
}
func HTTPMiddleware(opts MiddlewareOpts) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
err := Call(func() error {
next.ServeHTTP(w, r)
return nil
})
if err != nil {
if errors.Is(err, http.ErrAbortHandler) {
// we don't recover http.ErrAbortHandler so the response
// to the client is aborted, this should not be logged
panic(err)
}
if r.Header.Get("Connection") != "Upgrade" {
w.WriteHeader(http.StatusInternalServerError)
}
handler := opts.ErrorHandler
if handler == nil {
handler = SlogHandler(SlogHandlerOpts{StackPrint: StackPrintStructured})
}
handler(r.Context(), err)
}
}
return http.HandlerFunc(fn)
}
}