give me a golang grpc demo code
时间: 2023-03-20 13:02:23 浏览: 144
Sure! Here is a simple gRPC demo code written in Go:
```go
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
pb "path/to/your/protobuf/package" // import your protobuf package
)
type server struct {
pb.UnimplementedYourServiceServer // implement your service interface generated by protobuf
}
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloResponse, error) {
log.Printf("Received: %v", in.GetName())
return &pb.HelloResponse{Message: "Hello " + in.GetName()}, nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterYourServiceServer(s, &server{})
log.Println("Starting server on port :50051")
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
```
In this example, we define a `server` struct that implements the `YourServiceServer` interface generated by protobuf. We then define a `SayHello` function which receives a `HelloRequest` and returns a `HelloResponse`.
We then create a new gRPC server, register our `server` with it, and start serving on port 50051.
You will need to replace `path/to/your/protobuf/package` with the actual import path of your protobuf package, and `YourServiceServer` with the name of the service interface generated by protobuf.
阅读全文