grpc-ping/ping_server/main.go

50 lines
1003 B
Go
Raw Permalink Normal View History

2021-07-07 15:13:36 +00:00
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
2021-07-11 18:42:04 +00:00
pb "grpc-ping/ping"
2021-07-07 15:13:36 +00:00
)
const (
port = ":50051"
)
type server struct {
pb.UnimplementedPingServer
}
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func (s *server) Ping(ctx context.Context, req *pb.PingRequest) (*pb.PingResponse, error) {
2021-07-11 18:42:45 +00:00
log.Printf("Received: %v seq=%d", req.Data, req.Seq)
log.Printf("Sent: %v seq=%d", Reverse(req.Data), req.Seq)
2021-07-07 15:13:36 +00:00
return &pb.PingResponse{Data: Reverse(req.Data), Seq: req.Seq}, nil
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterPingServer(s, &server{})
log.Printf("server listening at %v", lis.Addr())
reflection.Register(s)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}