Golang gRPC

gRPC is an open-source, high-performance, general RPC framework that uses HTTP/2. It is the Golang (Go) implementation of gRPC.

Remote Procedure Call (RPC) is a distributed computing technique in which a computer program calls a procedure to execute in a different address space than its own. The RPC frameworks handle how that remote interaction is carried out.

Installation

  1. Download and install:
$ go get -u google.golang.org/grpc
  1. Import into your code:
import "google.golang.org/grpc"

Building a simple gRPC server

Here is an example of a simple gRPC server that listens on the 5000 port. The server does not do much, but we can add functionality by defining .proto files and generate the Go specific gRPC code using a Protocol Buffers tool.

package main
import (
"log"
"net"
"google.golang.org/grpc"
)
func main() {
// Setting up a tcp connection on port 5000
listener, error := net.Listen("tcp", ":5000")
if error != nil {
log.Fatalf("Failed to listen: %v", err)
}
// Creating the gRPC server
grpcServer := grpc.NewServer()
// Serving on the listener
err := grpcServer.Serve(listener);
if err != nil {
log.Fatalf("Failed to serve: %s", err)
}
}

You can read the entire gRPC API here.

Copyright ©2024 Educative, Inc. All rights reserved