You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by GitBox <gi...@apache.org> on 2022/03/20 11:58:01 UTC

[GitHub] [apisix] spacewander commented on a change in pull request #6653: refactor: merge grpc_server_example

spacewander commented on a change in pull request #6653:
URL: https://github.com/apache/apisix/pull/6653#discussion_r830605106



##########
File path: t/grpc_server_example/main.go
##########
@@ -0,0 +1,254 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+
+// 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
+}
+
+// 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
+}
+
+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)
+		}
+	}
+}
+
+func (s *server) Run(ctx context.Context, in *pb.Request) (*pb.Response, error) {
+	return &pb.Response{Body: in.User.Name + " " + in.Body}, nil
+}

Review comment:
       It is used in https://github.com/apache/apisix/blob/6bb9feac824f0640e0e4ab799e37bbbf3adcdd96/t/plugin/grpc-transcode2.t#L264




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org