-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
43 lines (37 loc) · 974 Bytes
/
chain.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
package slogx
import (
"context"
"log/slog"
)
// Chain is a chain of middleware.
type Chain struct {
mws []Middleware
slog.Handler
}
// NewChain returns a new Chain with the given middleware.
func NewChain(base slog.Handler, mws ...Middleware) *Chain {
return &Chain{mws: mws, Handler: base}
}
// Handle runs the chain of middleware and the handler.
func (c *Chain) Handle(ctx context.Context, rec slog.Record) error {
h := c.Handler.Handle
for i := len(c.mws) - 1; i >= 0; i-- {
h = c.mws[i](h)
}
return h(ctx, rec)
}
// WithGroup returns a new Chain with the given group.
// It applies middlewares on the top-level handler.
func (c *Chain) WithGroup(group string) slog.Handler {
return &Chain{
mws: c.mws,
Handler: c.Handler.WithGroup(group),
}
}
// WithAttrs returns a new Chain with the given attributes.
func (c *Chain) WithAttrs(attrs []slog.Attr) slog.Handler {
return &Chain{
mws: c.mws,
Handler: c.Handler.WithAttrs(attrs),
}
}