-
Notifications
You must be signed in to change notification settings - Fork 82
/
warning.go
82 lines (69 loc) · 1.56 KB
/
warning.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
// Package warning is used to handle HTTP warning headers
package warning
import (
"context"
"sync"
"github.com/sirupsen/logrus"
)
type contextKey string
var key contextKey = "key"
type Warning struct {
List []string
Hook *func(context.Context, *logrus.Logger, string)
mu sync.Mutex
}
func (w *Warning) Handle(ctx context.Context, log *logrus.Logger, msg string) {
w.mu.Lock()
defer w.mu.Unlock()
// dedup
for _, entry := range w.List {
if entry == msg {
return
}
}
w.List = append(w.List, msg)
// handle new warning if hook defined
if w.Hook != nil {
(*w.Hook)(ctx, log, msg)
}
}
func NewContext(ctx context.Context, w *Warning) context.Context {
return context.WithValue(ctx, key, w)
}
func FromContext(ctx context.Context) *Warning {
wAny := ctx.Value(key)
if wAny == nil {
return nil
}
w, ok := wAny.(*Warning)
if !ok {
return nil
}
return w
}
func NewHook(log *logrus.Logger) *func(context.Context, *logrus.Logger, string) {
hook := func(_ context.Context, _ *logrus.Logger, msg string) {
logMsg(log, msg)
}
return &hook
}
func DefaultHook() *func(context.Context, *logrus.Logger, string) {
hook := func(_ context.Context, log *logrus.Logger, msg string) {
logMsg(log, msg)
}
return &hook
}
func Handle(ctx context.Context, log *logrus.Logger, msg string) {
// check for context
if w := FromContext(ctx); w != nil {
w.Handle(ctx, log, msg)
return
}
// fallback to log
logMsg(log, msg)
}
func logMsg(log *logrus.Logger, msg string) {
log.WithFields(logrus.Fields{
"warning": msg,
}).Warn("Registry warning message")
}