// - proto/unary.proto -
syntax="proto3";optiongo_package="proto;unary_proto";packageua.made.unary;// The greeting service definition.
serviceService{// Sends a greeting
rpcHello(Request)returns(Reply){}}// The request message containing the user's name.
messageRequest{stringmessage=1;}// The response message containing the greetings
messageReply{stringmessage=1;}
// - server.go -
// Package main implements a server for Greeter service.
packagemainimport("context""fmt""log""net"pb"github.com/butuzov/sandbox/grpc/simple-rpc/proto""google.golang.org/grpc""google.golang.org/grpc/reflection")const(address="localhost:4772")// server is used to implement helloworld.GreeterServer.
typeserverstruct{pb.UnimplementedServiceServer}var_pb.ServiceServer=(*server)(nil)// SayHello implements helloworld.GreeterServer
func(s*server)Hello(ctxcontext.Context,in*pb.Request)(*pb.Reply,error){log.Printf("(incoming server) %#v \n",in.GetMessage())switchin.GetMessage(){case"Ping":return&pb.Reply{Message:"Pong"},nil}return&pb.Reply{Message:"<echo>"+in.GetMessage()},nil}funcmain(){listener,err:=net.Listen("tcp",address)iferr!=nil{log.Fatalf("failed to listen: %v",err)}fmt.Println("SERVER RUNS@",listener.Addr().String())s:=grpc.NewServer()pb.RegisterServiceServer(s,&server{})reflection.Register(s)log.Fatalf("failed to serve: %v",s.Serve(listener))}
// - client.go -
packagemainimport("context""log"pb"github.com/butuzov/sandbox/grpc/simple-rpc/proto""google.golang.org/grpc")const(address="localhost:4772")funcmain(){conn,err:=grpc.Dial(address,grpc.WithInsecure())iferr!=nil{log.Fatalf("did not connect: %v",err)}deferconn.Close()c:=pb.NewServiceClient(conn)ifresponse,err:=c.Hello(context.Background(),&pb.Request{Message:"Ping"});err!=nil{log.Fatalf("Error connecting to server: %v",err)}else{log.Printf("(incoming client) %#v \n",response.GetMessage())}}