Implement a gRPC Server

Distributed Services with Go — by Travis Jeffery (34 / 84)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Compile with the gRPC Plugin | TOC | Register Your Server 👉

Because the compiler generated a server stub, the job left for us is to write it. To implement a server, you need to build a struct whose methods match the service definition in your protobuf.

Create an internal/server directory tree in the root of your project by running mkdir -p internal/server. Internal packages are magical packages in Go that can only be imported by nearby code. For example, you can import code in /a/b/c/internal/d/e/f by code rooted by /a/b/c, but not code rooted by /a/b/g. In this directory, we’ll implement our server in a file called server.go and a package named server. The first order of business is to define our server type and a factory function to create an instance of the server.

Here’s the code we need to add to our server.go file:

ServeRequestsWithgRPC/internal/server/server.go

​ ​package​ server

​ ​import​ (
​ ​"context"​

​ api ​"github.com/travisjeffery/proglog/api/v1"​
​ ​"google.golang.org/grpc"​
​ )

​ ​type​ Config ​struct​ {
​ CommitLog CommitLog
​ }

​ ​var​ _ api.LogServer = (*grpcServer)(nil)

​ ​type​ grpcServer ​struct​ {
​ api.UnimplementedLogServer
​ *Config
​ }

​ ​func​ newgrpcServer(config *Config) (srv *grpcServer, err ​error​) {
​ srv = &grpcServer{
​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.