-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.go
283 lines (243 loc) · 8.13 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
//go:generate protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/helloworld.proto
//go:generate protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/import.proto
//go:generate protoc --include_imports --descriptor_set_out=proto.pb --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/src.proto
//go:generate protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/echo.proto
// Package main implements a server for Greeter service.
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/signal"
"syscall"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
pb "github.com/api7/grpc_server_example/proto"
)
var (
grpcAddr = ":50051"
grpcsAddr = ":50052"
grpcsMtlsAddr string
crtFilePath = "../t/cert/apisix.crt"
keyFilePath = "../t/cert/apisix.key"
caFilePath string
)
func init() {
flag.StringVar(&grpcAddr, "grpc-address", grpcAddr, "address for grpc")
flag.StringVar(&grpcsAddr, "grpcs-address", grpcsAddr, "address for grpcs")
flag.StringVar(&grpcsMtlsAddr, "grpcs-mtls-address", grpcsMtlsAddr, "address for grpcs in mTLS")
flag.StringVar(&crtFilePath, "crt", crtFilePath, "path to certificate")
flag.StringVar(&keyFilePath, "key", keyFilePath, "path to key")
flag.StringVar(&caFilePath, "ca", caFilePath, "path to ca")
}
// server is used to implement helloworld.GreeterServer.
type server struct {
// Embed the unimplemented server
pb.UnimplementedGreeterServer
pb.UnimplementedTestImportServer
pb.UnimplementedEchoServiceServer
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.Name)
log.Printf("Enum Gender: %v", in.GetGender())
msg := "Hello " + in.Name
person := in.GetPerson()
if person != nil {
if person.GetName() != "" {
msg += fmt.Sprintf(", name: %v", person.GetName())
}
if person.GetAge() != 0 {
msg += fmt.Sprintf(", age: %v", person.GetAge())
}
}
return &pb.HelloReply{
Message: msg,
Items: in.GetItems(),
Gender: in.GetGender(),
}, nil
}
// GetErrResp implements helloworld.GreeterServer
func (s *server) GetErrResp(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
st := status.New(codes.Unavailable, "Out of service")
st, err := st.WithDetails(&pb.ErrorDetail{
Code: 1,
Message: "The server is out of service",
Type: "service",
})
if err != nil {
panic(fmt.Sprintf("Unexpected error attaching metadata: %v", err))
}
return nil, st.Err()
}
func (s *server) SayHelloAfterDelay(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
errStr := ctx.Err().Error()
if ctx.Err() == context.DeadlineExceeded {
return nil, status.Error(codes.DeadlineExceeded, errStr)
}
}
time.Sleep(1 * time.Second)
log.Printf("Received: %v", in.Name)
return &pb.HelloReply{Message: "Hello delay " + in.Name}, nil
}
func (s *server) Plus(ctx context.Context, in *pb.PlusRequest) (*pb.PlusReply, error) {
log.Printf("Received: %v %v", in.A, in.B)
return &pb.PlusReply{Result: in.A + in.B}, nil
}
// SayHelloServerStream streams HelloReply back to the client.
func (s *server) SayHelloServerStream(req *pb.HelloRequest, stream pb.Greeter_SayHelloServerStreamServer) error {
log.Printf("Received server side stream req: %v\n", req)
// Say Hello 5 times.
for i := 0; i < 5; i++ {
if err := stream.Send(&pb.HelloReply{
Message: fmt.Sprintf("Hello %s", req.Name),
}); err != nil {
return status.Errorf(codes.Unavailable, "Unable to stream request back to client: %v", err)
}
}
return nil
}
// SayHelloClientStream receives a stream of HelloRequest from a client.
func (s *server) SayHelloClientStream(stream pb.Greeter_SayHelloClientStreamServer) error {
log.Println("SayHello client side streaming has been initiated.")
cache := ""
for {
req, err := stream.Recv()
if err == io.EOF {
return stream.SendAndClose(&pb.HelloReply{Message: cache})
}
if err != nil {
return status.Errorf(codes.Unavailable, "Failed to read client stream: %v", err)
}
cache = fmt.Sprintf("%sHello %s!", cache, req.Name)
}
}
// SayHelloBidirectionalStream establishes a bidirectional stream with the client.
func (s *server) SayHelloBidirectionalStream(stream pb.Greeter_SayHelloBidirectionalStreamServer) error {
log.Println("SayHello bidirectional streaming has been initiated.")
for {
req, err := stream.Recv()
if err == io.EOF {
return stream.Send(&pb.HelloReply{Message: "stream ended"})
}
if err != nil {
return status.Errorf(codes.Unavailable, "Failed to read client stream: %v", err)
}
// A small 0.5 sec sleep
time.Sleep(500 * time.Millisecond)
if err := stream.Send(&pb.HelloReply{Message: fmt.Sprintf("Hello %s", req.Name)}); err != nil {
return status.Errorf(codes.Unknown, "Failed to stream response back to client: %v", err)
}
}
}
// Echo implements echo.EchoService/Echo
func (s *server) Echo(ctx context.Context, in *pb.EchoMsg) (*pb.EchoMsg, error) {
msg := in.Msg
return &pb.EchoMsg{
Msg: msg,
}, nil
}
func (s *server) Run(ctx context.Context, in *pb.Request) (*pb.Response, error) {
return &pb.Response{Body: in.User.Name + " " + in.Body}, nil
}
func main() {
flag.Parse()
go func() {
lis, err := net.Listen("tcp", grpcAddr)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
reflection.Register(s)
pb.RegisterGreeterServer(s, &server{})
pb.RegisterTestImportServer(s, &server{})
pb.RegisterEchoServiceServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()
go func() {
lis, err := net.Listen("tcp", grpcsAddr)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
c, err := credentials.NewServerTLSFromFile(crtFilePath, keyFilePath)
if err != nil {
log.Fatalf("credentials.NewServerTLSFromFile err: %v", err)
}
s := grpc.NewServer(grpc.Creds(c))
reflection.Register(s)
pb.RegisterGreeterServer(s, &server{})
pb.RegisterEchoServiceServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()
if grpcsMtlsAddr != "" {
go func() {
lis, err := net.Listen("tcp", grpcsMtlsAddr)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
certificate, err := tls.LoadX509KeyPair(crtFilePath, keyFilePath)
if err != nil {
log.Fatalf("could not load server key pair: %s", err)
}
certPool := x509.NewCertPool()
ca, err := ioutil.ReadFile(caFilePath)
if err != nil {
log.Fatalf("could not read ca certificate: %s", err)
}
if ok := certPool.AppendCertsFromPEM(ca); !ok {
log.Fatalf("failed to append client certs")
}
c := credentials.NewTLS(&tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{certificate},
ClientCAs: certPool,
})
s := grpc.NewServer(grpc.Creds(c))
reflection.Register(s)
pb.RegisterGreeterServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()
}
signals := make(chan os.Signal)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
sig := <-signals
log.Printf("get signal %s, exit\n", sig.String())
}