-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgrpc.go
81 lines (70 loc) · 2.24 KB
/
grpc.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
package grpc
import (
"net"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
"time"
)
// New build a grpc server with interceptors
func New(interceptors ...grpc.UnaryServerInterceptor) *grpc.Server {
return grpc.NewServer(grpc.UnaryInterceptor(UnaryInterceptorChain(interceptors...)))
}
// Run make the grpc server start serve on host
func Run(gServer *grpc.Server, host string) {
reflection.Register(gServer)
lis, err := net.Listen("tcp", host)
if err != nil {
log.Fatal(err)
}
log.Info("grpc service listen on", host)
if err := gServer.Serve(lis); err != nil {
log.Fatal(err)
}
}
// UnaryInterceptorChain wrap interceptors in one interceptor
func UnaryInterceptorChain(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
return func(c context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
handlerChain := handler
for i := len(interceptors) - 1; i >= 0; i-- {
handlerChain = buildHandler(interceptors[i], info, handlerChain)
}
return handlerChain(c, req)
}
}
func buildHandler(interceptor grpc.UnaryServerInterceptor, info *grpc.UnaryServerInfo, handlerChain grpc.UnaryHandler) grpc.UnaryHandler {
return func(c context.Context, req interface{}) (interface{}, error) {
return interceptor(c, req, info, handlerChain)
}
}
// Recovery is an interceptor to recover when request deal panic
func Recovery(c context.Context, param interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
defer func() {
if err := recover(); err != nil {
err = grpc.Errorf(codes.Internal, "panic error: %v", err)
log.Error("[panic]", err)
return
}
}()
return handler(c, param)
}
// Logger is an interceptor to log request info
func Logger(c context.Context, param interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
start := time.Now()
resp, err = handler(c, param)
end := time.Now()
method := info.FullMethod
latency := end.Sub(start)
log.Info(
"-", // remote ip
end.Format("2006/01/02 15:04:05"),
latency.Nanoseconds(),
method,
"-", // trace id
"-", // uuid
param,
resp,
)
return
}