
To create a Golang gRPC server, you need to define a service with the `service` keyword, as seen in the "Defining a gRPC Service" section. This service will contain the methods that clients can call.
The service definition should include the method names and their corresponding request and response types. For example, in the "Defining a gRPC Service" section, we see a service called `Greeter` with a method called `SayHello`.
On the client side, you'll need to create a stub using the `protoc` compiler and the `grpc` package. The stub will provide the methods that you can call on the server. The "Creating a gRPC Client" section shows how to create a client stub from a generated protocol buffer file.
To call a method on the server, you'll need to create a request object and pass it to the corresponding method on the client stub. The request object should match the type of the method's request parameter.
You might like: C# Grpc Service
You might enjoy: Grpc Tutorial
Prerequisites
To get started with golang grpc, you'll need to meet some prerequisites.
First and foremost, you'll need to have Go installed on your system. This means installing any one of the two latest major releases of Go, which you can find instructions for in Go's Getting Started guide.
To work with protocol buffers, you'll also need to install the protocol buffer compiler, protoc, version 3. You can find installation instructions in the Protocol Buffer Compiler Installation guide.
Go plugins for the protocol compiler are also required, but the installation instructions for these can be found in the relevant resources.
On a similar theme: Golang Go
Project Setup
To set up your Go project for gRPC, start by initializing a new directory for your project. This will serve as the foundation for your application.
First, create a new directory for your project and navigate to it. From there, create three subdirectories: one for your Go client application, one for your Go server application, and one for your Hello World gRPC service.
Related reading: Go vs Golang
In the helloworld directory, create a file called helloworld.proto and add the code that defines your gRPC service and method request and response types using protocol buffers.
You'll need to install the gRPC-Go library and the protocol buffer compiler (protoc) to proceed. For Linux, the installation command for protoc is `sudo apt-get install protobuf-compiler`. Additionally, install Golang code generators for the protocol buffer using the following command: `go install google.golang.org/protobuf/cmd/[email protected]` and `go install google.golang.org/grpc/cmd/[email protected]`. Make sure to add these binaries to your path.
Here are the steps to create your project structure:
- Create a new directory for your project
- Create three subdirectories: client, server, and helloworld
- Navigate to the helloworld directory and create a file called helloworld.proto
- Install the gRPC-Go library and the protocol buffer compiler (protoc)
- Install Golang code generators for the protocol buffer
Now your project is set up and ready for you to start building your gRPC application.
Message Definitions
In golang grpc, message definitions are a crucial part of defining the data structure of a service.
You've likely created a service called Notes that performs two actions: Save a note and Load a note. These actions use the rpc communication protocol.
The Save function takes a Note (composed of a title and a body) as input and returns NoteSaveReply, which contains a Boolean to confirm if the note was saved.
Note that the types aren't the same as in Go, so be sure to check the language guide to start on the right foundation.
The data-structure definition is now complete, and you'll generate the related code using protoc, the compiler for protocol buffer definitions files.
Server Implementation
To implement a Go server application using gRPC, you first need to create a file called main.go in the server directory. This file should contain the code that implements the service interface generated from your service definition in the helloworld.proto file.
The code should provision a gRPC server and listen to requests on port 50051 from clients. However, you still need to implement your Go client application, so let's keep going.
To create the missing directories and files, type the following commands. This will set up the necessary file structure for your gRPC server.
Readers also liked: Golang Source
Once you have the file structure set up, you can implement the service by creating a struct that implements the gRPC interface. For example, you can create a struct called OrderService to implement the gRPC interface and add the same method signature as given in the interface definition for the AddOrder method.
To create a mock version of an in-memory database, you can use an array to store orders. You can place the following code in the internal/db.go file to create the mock database.
To start the gRPC server, you can add the following code to the cmd/server/main.go file. This will start a gRPC server listening on port 50051 using the mock database you created.
You can run the server by typing the following command. This will start the server and you should receive a message similar to this:
To create an API gateway server to invoke methods in a manner similar to the REST paradigm, you can create a new HTTP server that receives requests and executes the relevant gRPC methods for the orders service.
Broaden your view: Golang Add to Map
Client Implementation
To implement a gRPC client in Go, you'll need to create a file called main.go in the client directory. This file will contain the code to establish a connection to the gRPC server and perform RPCs.
The code for the main.go file will create a gRPC channel to communicate with the gRPC server, and a gRPC stub (client) to perform RPCs. You can use the code generated by protoc to create the client, which will be used to call the SayHello function on the gRPC server.
Here's a basic structure for the client configuration:
- Create a folder called notes_client and a main.go file inside it.
- Implement the minimal client configuration, then add the gRPC elements.
- Use the code generated by protoc and the client constructor NewNotesClient to establish the connection.
To use the client, you'll need to create a testdata folder to hold your notes. You can then try to save and load notes using the client.
Here are the basic steps to follow:
1. Create a folder called notes_client and a main.go file inside it.
2. Implement the minimal client configuration and add the gRPC elements.
3. Use the client to save and load notes.
Note that you'll need to handle errors when using the client, as gRPC has its own way of handling errors different from REST services.
Example Code
To get started with golang grpc, you'll need to download the example code. You can do this by downloading the repo as a zip file and unzipping it, or by cloning the repo using the command `git clone -b v1.75.0 --depth 1 https://github.com/grpc/grpc-go`.
Once you have the code, change into the quick start example directory using the command `cd grpc-go/examples/helloworld`. This will get you ready to run the example.
To run the example, navigate to the examples/helloworld directory and compile and execute the server code using the command `go run greeter_server/main.go`. From a different terminal, compile and execute the client code to see the client output, using the command `go run greeter_client/main.go`. You should see the greeting "Hello world" printed out.
Expand your knowledge: Golang Test Main
The client code is generated using protoc, which is also used to generate the service code. When you use the `--go-grpc_out` flag with protoc, it creates the client code for you. For example, it might look something like this:
To initialize the client, you'll need to create an active connection and a context. The context is used to track request-specific details, and you can build it with a timeout to prevent the service from hanging your client. For example, you might initialize the client and context like this:
Expand your knowledge: Golang Initialize Map
Run The Example
To run a gRPC client-server application in Go, you'll need to navigate to the examples/helloworld directory.
First, compile and execute the server code by running the command: go run greeter_server/main.go
Next, from a different terminal, compile and execute the client code to see the client output. You can do this by running the command: go run greeter_client/main.go
You should see the greeting "Hello world" displayed in the client output.
Testing and Error Handling
Testing and error handling are crucial aspects of gRPC development. Proper error handling ensures that your gRPC service can gracefully handle unexpected situations and provide meaningful feedback to the client.
Use unit tests to test the service logic and integration tests to test the client and server interaction. This helps catch bugs early and ensures that your service is reliable.
You can use error handling mechanisms, such as error codes and error messages, to handle errors. For example, the code checks if the name field is empty and returns an error if it is.
Here are some best practices to follow for testing and error handling:
- Use unit tests to test the service logic
- Use integration tests to test the client and server interaction
- Use error handling mechanisms, such as error codes and error messages, to handle errors
- Use logging mechanisms to log errors and other important events
Testing a Server
Testing a server is crucial to ensure it's working as expected. To test a gRPC server, you can use grpcurl.
To get started, you need to change your test script to use grpcurl. This is done by replacing the test.sh script with the grpcurl command.
A unique perspective: When to Use Grpc
Make sure your test-deps container has grpcurl installed. You can do this by copying it from the official grpcurl alpine image into your test-deps image.
With grpcurl, you can run end-to-end tests in CI, just like in the example where a gRPC server example was working and had end-to-end tests running in CI.
Testing a server also involves testing its entire flow in an end-to-end fashion. You can use a Postman collection to test the whole flow, just like in the example where a test suite for Postman was provided to optionally use to test the whole flow in an end-to-end fashion.
Error Testing
Error testing is a crucial aspect of gRPC development. It's essential to ensure that your service can handle errors gracefully and provide meaningful feedback to the client.
You can use unit tests to test the service logic, integration tests to test the client and server interaction, and error handling mechanisms to handle errors. For example, you can use error codes and error messages to handle errors.
Curious to learn more? Check out: Golang Create Error
Here are some best practices for error testing:
- Use unit tests to test the service logic
- Use integration tests to test the client and server interaction
- Use error handling mechanisms, such as error codes and error messages, to handle errors
By following these best practices, you can ensure that your gRPC service is robust and can handle errors effectively. Proper error handling ensures that your service can provide meaningful feedback to the client.
For instance, if you're handling errors like this:
You can use proper gRPC status codes to handle errors, like this:
This way, your client can understand the error message without being coupled to the exact strings used by your server.
Advanced Topics
gRPC supports three types of streaming protocols: server streaming, client streaming, and bidirectional streaming.
To implement a SaveLargeNote function that utilizes streaming, you need to update your service definition in notes.proto to include the stream keyword, which indicates the direction of the stream. This is used on the caller side for client-server streaming.
Server-side, you can consume a packet from the stream using stream.Recv(), and the stream will end when an io.EOF error is encountered. To close the stream and send a response to the client, use stream.SendAndClose.
Here are the key elements to note when using gRPC streaming on the server-side:
- stream.Recv() lets you consume a packet (the order of packets in a stream is preserved)
- io.EOF error ends a stream
- stream.SendAndClose is used to close the stream and send the response to the client
Why Is GraphQL Faster than REST?

GraphQL is faster than REST due to its ability to optimize data transfer and reduce overhead. This is achieved through its use of a single request that can fetch multiple resources, as opposed to the multiple requests required by REST.
gRPC, another high-performance API, also uses a single request to fetch multiple resources, but it achieves this through multiplexing over a single TCP connection. This is made possible by the HTTP/2 protocol, which offers several performance improvements.
One key feature of HTTP/2 is header compression and reuse, which reduces the size of messages. This is especially beneficial for protocols like gRPC, which use binary formats like protocol buffers to represent data.
Protocol buffers provide a more efficient binary data representation than text-based formats like JSON or XML. This results in significantly smaller message sizes, which further improves performance.
Here are some key differences between gRPC and GraphQL:
By leveraging these features, GraphQL and gRPC can both achieve better performance than traditional REST-based APIs.
Going Further

gRPC supports three types of streaming protocols: server streaming, client streaming, and bidirectional streaming.
To implement a SaveLargeNote function that utilizes streaming, you need to update your service definition in notes.proto to include the stream keyword.
The stream keyword on the function argument is on the caller side for client-server streaming.
You can generate the protocol buffer code using protoc with the same command as before.
The new SaveLargeNote function in the server code consumes a packet with stream.Recv(), and ends a stream with io.EOF error.
To close the stream and send the response to the client, you use stream.SendAndClose.
When using the save comment, if saveLargeBody is provided, then use the gRPC stream.
To create the stream, you need to split the Body into chunks.
The stream.Send() method sends a packet to the stream, and stream.CloseAndRecv() closes the stream and waits for the server response.
Here are the key elements of the new SaveLargeNote function:
- stream.Recv() lets you consume a packet (the order of packets in a stream is preserved)
- io.EOF error ends a stream
- stream.SendAndClose is used to close the stream and send the response to the client
- stream.Send sends a packet to the stream
- stream.CloseAndRecv closes the stream and waits for the server response
Protobuf and Code Generation
To use gRPC in Go, you need to install the protocol buffer compiler, protoc, which can be done using a package manager under Linux or macOS. You can also download the zip file from the Protocol Buffers downloads page and install it manually.
The protoc compiler generates code for populating, serializing, and retrieving message types, as well as client and server code. To regenerate the gRPC code, you need to run the protoc command with the --go-grpc_out and --go-grpc_opt arguments.
Here are the necessary files generated by protoc:
- Code for populating, serializing, and retrieving message types.
- Generated client and server code.
These files are generated from the .proto file, which defines the service and message types. To compile the service definition, you need to have a gRPC-specific binary installed, which can be installed using the following command:
Install Protobuf Compiler
To install the Protocol Buffer compiler, you can use a package manager like apt or Homebrew. On Linux, you can install it by typing `sudo apt install protobuf-compiler` or `sudo apt install libprotobuf-dev libprotoc-dev`, while on macOS, you can use Homebrew with the command `brew install protobuf`.
If you prefer to build the compiler from sources or access older versions, you can visit the Protocol Buffers downloads page. This will give you more control over the installation process, but it's generally easier to use a package manager.
You can also install the compiler by downloading the zip file from the Protocol Buffers releases page and unzipping it under `$HOME/.local`. After that, you'll need to update your environment's PATH variable to include the path to the protoc executable.
Here are the steps to follow:
- Download the zip file from the Protocol Buffers releases page
- Unzip it under `$HOME/.local`
- Update your environment's PATH variable to include the path to the protoc executable
Note that if your `.bash_profile` or `.zshrc` file already contains an export path, you can simply append `:$HOME/.local/bin` to it.
Protoc and Generated Code
You can install protoc via an OS package manager like brew, but it has some downsides. Installing it this way can be a quick way to get started.
To generate the necessary files, you'll need to run the protoc command with the appropriate flags. For example, you can use --go-grpc_out and --go-grpc_opt to generate gRPC code.
The protoc command can be used to generate code for multiple languages, including Go. This is useful if you need to work with data in different languages.
Here's a list of some of the benefits of using Protocol Buffers:
- Efficient serialization and deserialization
- Platform independence
- Schema migration support
- Language independence
To make the generated code work in your system, you may need to install additional dependencies. For example, you may need to install the gRPC dependency.
The Makefile can be modified to include the necessary flags for generating gRPC code. This can be done by adding the --go-grpc_out and --go-grpc_opt flags to the protoc command.
The protoc command can be run multiple times to generate different types of code. For example, you can use the --go_out flag to generate Go code, and the --go-grpc_out flag to generate gRPC code.
To ensure that the protoc command is installed correctly, you can check the output to see if the expected files are generated. For example, you can check if the order_grpc.pb.go file is generated when using the --go-grpc_out flag.
Docker Setup
Let's improve the developer experience by incorporating Docker and docker-compose in our setup. This will also prove highly beneficial in the upcoming deployment of services through Koyeb.
We can add a Dockerfile to the root of our project to build the two servers as two Docker targets using multi-stage builds. This includes an ORDER_SERVICE_ADDRESS build argument that is passed to go build as an ldflag.
The ORDER_SERVICE_ADDRESS variable is exposed during the compilation process. We can modify our gateway service code to accommodate this variable by modifying the cmd/client/main.go file.
We can add a docker-compose file to serve both services locally. Create a docker-compose.yaml file in the project root directory with the following configuration:
This configuration enables services to discover and communicate with each other using service names as hostnames. We've specified build targets in each service that we define and set the ORDER_SERVICE_ADDRESS variable to order-service (the service name of the order service) followed by the port number.
You can start both services by typing "docker-compose up" to build the images and start the services.
API Gateway and Setup
To set up an API Gateway, you can use Google's grpc-gateway library to simplify the process. This library acts as a reverse proxy, providing a HTTP+JSON interface to the gRPC service.
Fortunately, grpc-gateway can be used to attach HTTP semantics to the service with just a small amount of configuration. This configuration requires two additional binaries and some adjustments to the service definition.
You'll need to add two new files to your proto/google/api folder: annotations.proto and http.proto. These files will provide the necessary definitions for the gateway to work.
Explore further: Golang Rest Api Framework
Deploy The Orders
To deploy the orders service, you'll need to access the Koyeb control panel and follow these steps.
Click Create Web Service on the Overview tab.
Select GitHub as the deployment method.
Choose your project from the GitHub repository list.
In the Builder section, select Dockerfile and enter orders-service in the Target field.
Set the Exposed ports section to 50051 and deselect the Public option to mark the service as internal.
Set the App name to orders-service and click Deploy.
Set Up API Gateway
To set up an API Gateway, you can use Google's grpc-gateway library to simplify the process of setting up a reverse proxy. This will act as a HTTP+JSON interface to the gRPC service.
The grpc-gateway library requires two additional binaries to help generate the gateway code. You'll need to add two new files to your proto/google/api folder: annotations.proto and http.proto.
The proto directory should now look like this: proto/google/api/annotations.proto, proto/google/api/http.proto. Next, modify the proto/orders/orders.proto file to add the gateway server changes.
Notice how you've designated AddOrder as a POST endpoint with the path as /v0/orders and body specified as "*". This indicates that the entire request body will be utilized as input for the AddOrder invocation.
Modify your Makefile to add the new gRPC gateway options to your existing protoc command. Use the Makefile to generate the necessary code again by typing: make protoc.
A new file will be created with the path protogen/golang/orders/order.pb.gw.go. This file contains a function called RegisterOrdersHandlerServer, with a function body that resembles a typical REST handler register.
A different take: Golang Api Gateway
Create a new file with the path cmd/client/main.go and start up both services by executing the following in two separate terminal windows: go run cmd/server/main.go and go run cmd/client/main.go.
Now, in a third terminal, send the payload to the server by typing: curl -X POST -H "Content-Type: application/json" -d '{"name": "John", "age": 30}' http://localhost:8080/v0/orders. You should receive a 200 status message indicating that the payload was accepted.
Frequently Asked Questions
Is gRPC really better than REST?
gRPC generally outperforms REST due to its use of HTTP/2 and Protocol Buffers, making it a better choice for high-priority performance needs. However, REST may still be a suitable option depending on the specific use case.
When should you use gRPC?
Use gRPC for high-performance systems that require real-time streaming and large data loads, especially in microservice architectures with multiple programming languages. It's ideal for stable APIs that won't change frequently.
What are the benefits of gRPC Golang?
gRPC Golang benefits include high performance and efficiency, thanks to its use of Protobufs and HTTP/2 multiplexing, which reduce latency and improve throughput. This makes gRPC Golang an ideal choice for building scalable and high-speed applications.
Featured Images: pexels.com


