Creating main.go

Before creating main.go file we are assuming that the user has created a go.mod with the name github.com/myuser/myrepo, if not please refer to Creating go.mod file. The import here is using the path to the generated files in proto/helloworld relative to the root of the repository.

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "net"
  6. "google.golang.org/grpc"
  7. helloworldpb "github.com/myuser/myrepo/proto/helloworld"
  8. )
  9. type server struct{
  10. helloworldpb.UnimplementedGreeterServer
  11. }
  12. func NewServer() *server {
  13. return &server{}
  14. }
  15. func (s *server) SayHello(ctx context.Context, in *helloworldpb.HelloRequest) (*helloworldpb.HelloReply, error) {
  16. return &helloworldpb.HelloReply{Message: in.Name + " world"}, nil
  17. }
  18. func main() {
  19. // Create a listener on TCP port
  20. lis, err := net.Listen("tcp", ":8080")
  21. if err != nil {
  22. log.Fatalln("Failed to listen:", err)
  23. }
  24. // Create a gRPC server object
  25. s := grpc.NewServer()
  26. // Attach the Greeter service to the server
  27. helloworldpb.RegisterGreeterServer(s, &server{})
  28. // Serve gRPC Server
  29. log.Println("Serving gRPC on 0.0.0.0:8080")
  30. log.Fatal(s.Serve(lis))
  31. }

Read More

For more refer to gRPC docs https://grpc.io/docs/languages/go/.

Next