-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_builder.go
More file actions
63 lines (53 loc) · 1.56 KB
/
server_builder.go
File metadata and controls
63 lines (53 loc) · 1.56 KB
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
package listener
import (
"runtime/debug"
"slices"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
)
type ServerBuilder struct {
unary []grpc.UnaryServerInterceptor
stream []grpc.StreamServerInterceptor
}
func NewServerBuilder() *ServerBuilder {
return &ServerBuilder{}
}
func (sb *ServerBuilder) AddUnary(u ...grpc.UnaryServerInterceptor) *ServerBuilder {
sb.unary = append(sb.unary, u...)
return sb
}
func (sb *ServerBuilder) AddStream(s ...grpc.StreamServerInterceptor) *ServerBuilder {
sb.stream = append(sb.stream, s...)
return sb
}
func (sb *ServerBuilder) Build() *grpc.Server {
unary, stream := createRecovery()
server := grpc.NewServer(
grpc.ChainUnaryInterceptor(
append(slices.Clone(sb.unary), unary)...,
),
grpc.ChainStreamInterceptor(
append(slices.Clone(sb.stream), stream)...,
),
)
healthcheck := health.NewServer()
healthpb.RegisterHealthServer(server, healthcheck)
reflection.Register(server)
return server
}
func createRecovery() (grpc.UnaryServerInterceptor, grpc.StreamServerInterceptor) {
opts := []recovery.Option{
recovery.WithRecoveryHandler(func(p any) error {
debug.PrintStack()
return status.Errorf(codes.Unknown, "panic triggered: %v", p)
}),
}
unary := recovery.UnaryServerInterceptor(opts...)
stream := recovery.StreamServerInterceptor(opts...)
return unary, stream
}