-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
middleware_inline.go
86 lines (75 loc) · 2.54 KB
/
middleware_inline.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
package slogmulti
import (
"context"
"log/slog"
)
// NewInlineMiddleware is a shortcut to a middleware that implements all methods.
func NewInlineMiddleware(
enabledFunc func(ctx context.Context, level slog.Level, next func(context.Context, slog.Level) bool) bool,
handleFunc func(ctx context.Context, record slog.Record, next func(context.Context, slog.Record) error) error,
withAttrsFunc func(attrs []slog.Attr, next func([]slog.Attr) slog.Handler) slog.Handler,
withGroupFunc func(name string, next func(string) slog.Handler) slog.Handler,
) Middleware {
return func(next slog.Handler) slog.Handler {
if next == nil {
panic("slog-multi: next is required")
}
if enabledFunc == nil {
panic("slog-multi: enabledFunc is required")
}
if handleFunc == nil {
panic("slog-multi: handleFunc is required")
}
if withAttrsFunc == nil {
panic("slog-multi: withAttrsFunc is required")
}
if withGroupFunc == nil {
panic("slog-multi: withGroupFunc is required")
}
return &InlineMiddleware{
next: next,
enabledFunc: enabledFunc,
handleFunc: handleFunc,
withAttrsFunc: withAttrsFunc,
withGroupFunc: withGroupFunc,
}
}
}
var _ slog.Handler = (*InlineMiddleware)(nil)
type InlineMiddleware struct {
next slog.Handler
enabledFunc func(ctx context.Context, level slog.Level, next func(context.Context, slog.Level) bool) bool
handleFunc func(ctx context.Context, record slog.Record, next func(context.Context, slog.Record) error) error
withAttrsFunc func(attrs []slog.Attr, next func([]slog.Attr) slog.Handler) slog.Handler
withGroupFunc func(name string, next func(string) slog.Handler) slog.Handler
}
// Implements slog.Handler
func (h *InlineMiddleware) Enabled(ctx context.Context, level slog.Level) bool {
return h.enabledFunc(ctx, level, h.next.Enabled)
}
// Implements slog.Handler
func (h *InlineMiddleware) Handle(ctx context.Context, record slog.Record) error {
return h.handleFunc(ctx, record, h.next.Handle)
}
// Implements slog.Handler
func (h *InlineMiddleware) WithAttrs(attrs []slog.Attr) slog.Handler {
return NewInlineMiddleware(
h.enabledFunc,
h.handleFunc,
h.withAttrsFunc,
h.withGroupFunc,
)(h.withAttrsFunc(attrs, h.next.WithAttrs))
}
// Implements slog.Handler
func (h *InlineMiddleware) WithGroup(name string) slog.Handler {
// https://cs.opensource.google/go/x/exp/+/46b07846:slog/handler.go;l=247
if name == "" {
return h
}
return NewInlineMiddleware(
h.enabledFunc,
h.handleFunc,
h.withAttrsFunc,
h.withGroupFunc,
)(h.withGroupFunc(name, h.next.WithGroup))
}