-
Notifications
You must be signed in to change notification settings - Fork 0
/
unary_server.go
73 lines (59 loc) · 1.82 KB
/
unary_server.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
package grpc_interceptor
import (
"context"
"google.golang.org/grpc"
)
type unaryServerInterceptorGroup struct {
ics []grpc.UnaryServerInterceptor
domain domain
}
type UnaryServerInterceptors struct {
s []unaryServerInterceptorGroup
}
func (usi *UnaryServerInterceptors) Add(interceptors ...grpc.UnaryServerInterceptor) *UnaryServerInterceptors {
usi.s = append(usi.s, unaryServerInterceptorGroup{
ics: interceptors,
domain: newDomain(),
})
return usi
}
func (usi *UnaryServerInterceptors) AddWithoutMethods(methods []string, interceptors ...grpc.UnaryServerInterceptor) *UnaryServerInterceptors {
usi.s = append(usi.s, unaryServerInterceptorGroup{
ics: interceptors,
domain: newBlackDomain(methods),
})
return usi
}
func (usi *UnaryServerInterceptors) AddOnMethods(methods []string, interceptors ...grpc.UnaryServerInterceptor) *UnaryServerInterceptors {
if len(methods) > 0 {
usi.s = append(usi.s, unaryServerInterceptorGroup{
ics: interceptors,
domain: newWhiteDomain(methods),
})
}
return usi
}
func (usi *UnaryServerInterceptors) UnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
if len(usi.s) == 0 {
return handler(ctx, req)
}
var cursor handleCursor
var chainHandler grpc.UnaryHandler
chainHandler = func(ctx context.Context, req interface{}) (interface{}, error) {
for cursor.segment < len(usi.s) {
group := usi.s[cursor.segment]
if group.domain.isOnMethod(info.FullMethod) && cursor.offset < len(group.ics) {
ic := group.ics[cursor.offset]
cursor.offset++
return ic(ctx, req, info, chainHandler)
}
cursor.offset = 0
cursor.segment++
}
return handler(ctx, req)
}
return chainHandler(ctx, req)
}
}