-
Notifications
You must be signed in to change notification settings - Fork 117
/
interceptor.go
52 lines (36 loc) · 1.33 KB
/
interceptor.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
package requestid
import (
"context"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"google.golang.org/grpc"
)
// UnaryServerInterceptor returns grpc.UnaryServerInterceptor
// that should be used as a middleware to generate/include Request-Id in headers and context
// for tracing and tracking user's request.
//
// Returned middleware populates Request-Id from gRPC metadata if
// they defined in a testRequest message else creates a new one.
func UnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (res interface{}, err error) {
reqID := HandleRequestID(ctx)
// add request id to logger
addRequestIDToLogger(ctx, reqID)
ctx = NewContext(ctx, reqID)
// returning from the request call
res, err = handler(ctx, req)
return
}
}
func StreamServerInterceptor() grpc.StreamServerInterceptor {
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
ctx := stream.Context()
reqID := HandleRequestID(ctx)
// add request id to logger
addRequestIDToLogger(ctx, reqID)
ctx = NewContext(ctx, reqID)
wrapped := grpc_middleware.WrapServerStream(stream)
wrapped.WrappedContext = ctx
err = handler(srv, wrapped)
return
}
}