/
grpc.go
54 lines (45 loc) · 1.7 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
package server
import (
"fmt"
"net"
"os"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus" // TODO github.com/grpc-ecosystem/go-grpc-middleware/v2 https://github.com/grpc-ecosystem/go-grpc-middleware/blob/main/interceptors/logging/examples/logrus/example_test.go
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"github.com/dowenliu-xyz/wild-workouts-go-ddd-walkthrough/internal/common/logs"
)
func init() {
logger := logrus.New()
logs.SetFormatter(logger)
logger.SetLevel(logrus.WarnLevel)
grpc_logrus.ReplaceGrpcLogger(logrus.NewEntry(logger))
}
func RunGRPCServer(registerServer func(server *grpc.Server)) {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
addr := fmt.Sprintf(":%s", port)
RunGRPCServerOnAddr(addr, registerServer)
}
func RunGRPCServerOnAddr(addr string, registerServer func(server *grpc.Server)) {
logrusEntry := logrus.NewEntry(logrus.StandardLogger())
grpcServer := grpc.NewServer(
grpc.ChainUnaryInterceptor(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_logrus.UnaryServerInterceptor(logrusEntry),
),
grpc.ChainStreamInterceptor(
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_logrus.StreamServerInterceptor(logrusEntry),
),
)
registerServer(grpcServer)
listen, err := net.Listen("tcp", addr)
if err != nil {
logrus.Fatal(err) // TODO ??? fatal?!!!
}
logrus.WithField("grpcEndpoint", addr).Info("Starting: gRPC Listener")
logrus.Fatal(grpcServer.Serve(listen)) // TODO ??? em... fatal again. what about returning error
}