/
interceptors.go
69 lines (56 loc) · 1.52 KB
/
interceptors.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
package interceptors
import (
"strings"
kitgrpc "github.com/go-kit/kit/transport/grpc"
"github.com/rs/zerolog"
"google.golang.org/grpc"
)
func getMethod(info *grpc.UnaryServerInfo) string {
splits := strings.Split(info.FullMethod, "/")
return splits[len(splits)-1]
}
type Interceptor interface {
Get() grpc.ServerOption
}
type interceptor struct {
options []grpc.UnaryServerInterceptor
skipMethods []string
}
func (i *interceptor) skipLog(method string) bool {
// quick good lookup function
for _, m := range i.skipMethods {
if m == method {
return true
}
}
return false
}
type InterceptorOption func(in *interceptor)
func WithInterecptor(userInterceptor grpc.UnaryServerInterceptor) InterceptorOption {
return func(in *interceptor) {
in.options = append(in.options, userInterceptor)
}
}
// Get return the unary interceptos composing of all default and user options
func (in *interceptor) Get() grpc.ServerOption {
return grpc.ChainUnaryInterceptor(
in.options...,
)
}
func WithSkipMethod(methods []string) InterceptorOption {
return func(in *interceptor) {
in.skipMethods = methods
}
}
func NewInterceptor(service string, logger zerolog.Logger, options ...InterceptorOption) Interceptor {
in := &interceptor{}
// apply default interceptors
WithInterecptor(kitgrpc.Interceptor)(in)
WithInterecptor(traceIdReader(in, logger))(in)
WithInterecptor(loggingInterceptor(in, logger))(in)
WithInterecptor(recoveryInterceptor(in, logger))(in)
for _, option := range options {
option(in)
}
return in
}