-
Notifications
You must be signed in to change notification settings - Fork 8
/
grpc.go
54 lines (46 loc) · 1.54 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/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/common/logs"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
)
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_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_logrus.UnaryServerInterceptor(logrusEntry),
),
grpc_middleware.WithStreamServerChain(
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)
}
logrus.WithField("grpcEndpoint", addr).Info("Starting: gRPC Listener")
logrus.Fatal(grpcServer.Serve(listen))
}