CodeBlanks Logo Icon CodeBlanks

gRPC server

Learn to set up a gRPC server and register a service.

A gRPC server

The server writes a type that satisfies the generated interface, registers it with a grpc.Server and serves on a TCP listener:

type sunucu struct {
    pb.UnimplementedSelamlayiciServer
}

func (sunucu) Selam(ctx context.Context, in *pb.SelamIstek) (*pb.SelamYanit, error) {
    return &pb.SelamYanit{Mesaj: "Merhaba " + in.GetAd()}, nil
}

lis, _ := net.Listen("tcp", ":50051")
s := grpc.NewServer()
pb.RegisterSelamlayiciServer(s, sunucu{})
s.Serve(lis)

Error codes

gRPC errors carry their own status codes instead of HTTP codes. The status package returns meaningful errors:

if in.GetAd() == "" {
    return nil, status.Error(codes.InvalidArgument, "ad boş olamaz")
}

The client reads the code with status.Code(err) and reacts to cases such as NotFound, Unauthenticated, DeadlineExceeded.

Practice A validating method

Write Selam(ad string) (string, error): if ad is empty return errors.New("ad boş olamaz"), otherwise "Merhaba " + ad. Print the error from Selam("").

Starter code

main.go
package main

import (
    "errors"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "errors"
    "fmt"
)

func Selam(ad string) (string, error) {
    if ad == "" {
        return "", errors.New("ad boş olamaz")
    }
    return "Merhaba " + ad, nil
}

func main() {
    _, err := Selam("")
    fmt.Println(err)
}

Expected output

ad boş olamaz

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is <code>UnimplementedSelamlayiciServer</code> embedded?

  • To speed up the server
  • To enable TLS
  • For logging
  • So the code keeps compiling when new methods are added to the proto Correct answer

Explanation: The embedded type provides defaults that return an "Unimplemented" error for methods you haven't written; it is for forward compatibility.

2 Register the service

Question
s := grpc.NewServer()
pb.____(s, sunucu{})
Answer
s := grpc.NewServer()
pb.RegisterSelamlayiciServer(s, sunucu{})

Explanation: The generated Register...Server function attaches the implementation to the server.

3 Server steps

Term Meaning
net.Listen Opens a port
grpc.NewServer Creates the server
Register...Server Attaches the service
s.Serve Serves requests

All lessons in Advanced