...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package grpc_testing
16
17 import (
18 "context"
19 "sync"
20
21 "google.golang.org/grpc"
22 "google.golang.org/grpc/metadata"
23 )
24
25 type GrpcRecorder struct {
26 mux sync.RWMutex
27 requests []RequestInfo
28 }
29
30 type RequestInfo struct {
31 FullMethod string
32 Authority string
33 }
34
35 func (ri *GrpcRecorder) UnaryInterceptor() grpc.UnaryServerInterceptor {
36 return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
37 ri.record(toRequestInfo(ctx, info))
38 resp, err := handler(ctx, req)
39 return resp, err
40 }
41 }
42
43 func (ri *GrpcRecorder) RecordedRequests() []RequestInfo {
44 ri.mux.RLock()
45 defer ri.mux.RUnlock()
46 reqs := make([]RequestInfo, len(ri.requests))
47 copy(reqs, ri.requests)
48 return reqs
49 }
50
51 func toRequestInfo(ctx context.Context, info *grpc.UnaryServerInfo) RequestInfo {
52 req := RequestInfo{
53 FullMethod: info.FullMethod,
54 }
55 md, ok := metadata.FromIncomingContext(ctx)
56 if ok {
57 as := md.Get(":authority")
58 if len(as) != 0 {
59 req.Authority = as[0]
60 }
61 }
62 return req
63 }
64
65 func (ri *GrpcRecorder) record(r RequestInfo) {
66 ri.mux.Lock()
67 defer ri.mux.Unlock()
68 ri.requests = append(ri.requests, r)
69 }
70
View as plain text