CodeBlanks Logo Icon CodeBlanks

Summary - gRPC

Combine server and client to write a gRPC service.

gRPC summary

The flow: write the contract in a .proto → generate Go code with protoc → on the server implement the interface, Register and Serve → on the client make calls with timeouts using NewClient + the generated client. Errors travel with status and codes.

Never change field numbers; mark removed ones reserved.

Interceptors

The gRPC counterpart of middleware is the interceptor. It is added to the server with the grpc.UnaryInterceptor(...) option and runs before/after every unary call:

func logla(ctx context.Context, req any, info *grpc.UnaryServerInfo, h grpc.UnaryHandler) (any, error) {
    bas := time.Now()
    resp, err := h(ctx, req)
    log.Println(info.FullMethod, time.Since(bas))
    return resp, err
}

Practice Interceptor simulation

Define type Handler func(string) string. Write intercept(h Handler) Handler: print ">" before the call and "<" after, then return the result. Print the result of intercept(func(s string) string { return s + "!" })("go").

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Handler func(string) string

func intercept(h Handler) Handler {
    return func(s string) string {
        fmt.Println(">")
        r := h(s)
        fmt.Println("<")
        return r
    }
}

func main() {
    fmt.Println(intercept(func(s string) string { return s + "!" })("go"))
}

Expected output

>
<
go!

Questions and answers

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

1 How does a client recognize a "resource not found" case?

  • When the response is empty
  • status.Code(err) == codes.NotFound Correct answer
  • err == nil
  • From an HTTP 404 header

Explanation: gRPC error codes are read through the status package; NotFound is the code the server returns with status.Error(codes.NotFound, ...).

2 Error code

Question
return nil, status.Error(codes.____, "ürün yok")
Answer
return nil, status.Error(codes.NotFound, "ürün yok")

Explanation: codes.NotFound is the gRPC status code reporting that the requested record doesn't exist.

3 Group summary

Term Meaning
.proto Contract
protoc Code generation
Interceptor gRPC middleware
codes.DeadlineExceeded Time ran out

All lessons in Advanced