-
Notifications
You must be signed in to change notification settings - Fork 5k
/
sanitizer.go
82 lines (68 loc) · 2.42 KB
/
sanitizer.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 grpc
import (
"errors"
"regexp"
"strings"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
)
const (
contextKey = "sanitizer"
)
// ErrorSanitizerUnaryServerInterceptor returns a new unary server interceptor that sanitizes error messages
// and provides Sanitizer to define replacements.
func ErrorSanitizerUnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
sanitizer := NewSanitizer()
resp, err = handler(ContextWithSanitizer(ctx, sanitizer), req)
if err == nil {
return resp, nil
}
if se, ok := err.(interface{ GRPCStatus() *status.Status }); ok {
return resp, status.Error(se.GRPCStatus().Code(), sanitizer.Replace(se.GRPCStatus().Message()))
}
return resp, errors.New(sanitizer.Replace(err.Error()))
}
}
// ContextWithSanitizer returns a new context with sanitizer set.
func ContextWithSanitizer(ctx context.Context, sanitizer Sanitizer) context.Context {
return context.WithValue(ctx, contextKey, sanitizer)
}
// SanitizerFromContext returns sanitizer from context.
func SanitizerFromContext(ctx context.Context) (Sanitizer, bool) {
res, ok := ctx.Value(contextKey).(Sanitizer)
return res, ok
}
// Sanitizer provides methods to define list of strings and replacements
type Sanitizer interface {
Replace(s string) string
AddReplacement(val string, replacement string)
AddRegexReplacement(regex *regexp.Regexp, replacement string)
}
type sanitizer struct {
replacers []func(in string) string
}
// NewSanitizer returns a new Sanitizer instance
func NewSanitizer() *sanitizer {
return &sanitizer{}
}
// AddReplacement adds a replacement to the Sanitizer
func (s *sanitizer) AddReplacement(val string, replacement string) {
s.replacers = append(s.replacers, func(in string) string {
return strings.Replace(in, val, replacement, -1)
})
}
// AddRegexReplacement adds a replacement to the sanitizer using regexp
func (s *sanitizer) AddRegexReplacement(regex *regexp.Regexp, replacement string) {
s.replacers = append(s.replacers, func(in string) string {
return regex.ReplaceAllString(in, replacement)
})
}
// Replace replaces all occurrences of the configured values in the sanitizer with the replacements
func (s *sanitizer) Replace(val string) string {
for _, replacer := range s.replacers {
val = replacer(val)
}
return val
}