Sling Academy
Home/Golang/Building gRPC Servers in Go

Building gRPC Servers in Go

Last updated: November 27, 2024

gRPC is a modern, open-source remote procedure call (RPC) framework that leverages HTTP/2 for transport, Protocol Buffers for serialization, and provides features like authentication, load balancing, and more. Building a gRPC server using Go allows you to take advantage of these features in a scalable and efficient way.

Setting Up Your Environment

Before you start building a gRPC server in Go, make sure you've set up your environment. Here are the prerequisites:

  • Go (version 1.13 or higher)
  • Protocol Buffers Compiler (protoc)
  • gRPC-Go library
  • gRPC tools for protoc plugin

To install the necessary Go packages, you can run the following commands:

go get google.golang.org/grpc
go get github.com/golang/protobuf/protoc-gen-go

Defining Your Service

First, define the service and messages using Protocol Buffers. Create a service.proto file with the service definitions:

syntax = "proto3";

package helloworld;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

Compiling the Protocol Buffer

Use the Protocol Buffers compiler to generate Go code from the .proto file. Run the following command:

protoc --go_out=. --go-grpc_out=. service.proto

This will generate two files: service.pb.go and service_grpc.pb.go, which contain the generated code for Protocol Buffers and gRPC stubs, respectively.

Implementing the gRPC Server

Now, let's implement the gRPC server. Create a new Go file called server.go and write the following code:

package main

import (
    "context"
    "log"
    "net"

    "google.golang.org/grpc"
    pb "path/to/generated/service/pb"
)

// server is used to implement helloworld.GreeterServer.
type server struct {
    pb.UnimplementedGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    log.Printf("Received: %v", in.GetName())
    return &pb.HelloReply{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.RegisterGreeterServer(s, &server{})
    log.Printf("server listening at %v", lis.Addr())
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

In the code snippet above, the SayHello function implements the GreeterServer interface. It takes a HelloRequest and responds with a HelloReply.

Running the gRPC Server

To run the server, simply execute the Go file:

go run server.go

Your gRPC server will start and listen for requests on port 50051. You can test your server using a gRPC client by sending a request and validating the response.

Conclusion

With these steps, you've built a simple gRPC server in Go. You can expand upon this basic structure to include features such as SSL/TLS encryption and authentication using interceptors to develop more production-ready applications.

Next Article: Interacting with External APIs in Go

Previous Article: Creating REST APIs with Go: Step-by-Step

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant