-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
128 lines (107 loc) · 2.43 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"context"
"fmt"
"log"
"net"
"os"
"os/signal"
"time"
"github.com/golang/protobuf/ptypes/timestamp"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"github.com/a2ush/grpc-echo-server/rpc"
)
type EchoServerHandler struct{}
type GreetingServerHandler struct {
name string
}
func NewServerHandler() *GreetingServerHandler {
return &GreetingServerHandler{
name: "GreetingBot",
}
}
func main() {
port := 50051
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatalf("failed to listen; %v", err)
}
// Add logger
zapLogger, err := zap.NewProduction()
if err != nil {
panic(err)
}
grpc_zap.ReplaceGrpcLogger(zapLogger)
server := grpc.NewServer(
grpc.UnaryInterceptor(
grpc_middleware.ChainUnaryServer(
grpc_zap.UnaryServerInterceptor(zapLogger),
),
),
)
rpc.RegisterEchoServer(
server,
&EchoServerHandler{},
)
rpc.RegisterGreatingServer(
server,
NewServerHandler(),
)
reflection.Register(server)
go func() {
log.Printf("start gRPC server port: %v", port)
server.Serve(lis)
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
log.Println("stopping gRPC server...")
server.GracefulStop()
}
func (s *GreetingServerHandler) Reply(
ctx context.Context,
req *rpc.GreatingClientRequest,
) (*rpc.ServerGreatingResponse, error) {
wording := ""
if req.ClientGreeting == rpc.Format_Unknown || req.ClientGreeting > rpc.Format_Casual {
wording = "hummm :( WHO ARE YOU?"
}
switch req.ClientGreeting {
case rpc.Format_Formal:
log.Printf("Formal")
wording = "How are you?"
case rpc.Format_Normal:
log.Printf("Normal")
wording = "Hello"
case rpc.Format_Casual:
log.Printf("Casual")
wording = "Hi :)"
}
return &rpc.ServerGreatingResponse{
Name: s.name,
Format: &rpc.Format{
Echo: wording,
},
CreateTime: ×tamp.Timestamp{
Seconds: time.Now().Unix(),
Nanos: int32(time.Now().Nanosecond()),
},
}, nil
}
func (s *EchoServerHandler) Reply(
ctx context.Context,
req *rpc.ClientRequest,
) (*rpc.ServerResponse, error) {
return &rpc.ServerResponse{
Name: "EchoBot",
Message: req.Message + " by EchoBot",
CreateTime: ×tamp.Timestamp{
Seconds: time.Now().Unix(),
Nanos: int32(time.Now().Nanosecond()),
},
}, nil
}