Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Last active August 6, 2021 11:35
Show Gist options
  • Save percybolmer/677fc087905212663a333d9cf74a01a5 to your computer and use it in GitHub Desktop.
Save percybolmer/677fc087905212663a333d9cf74a01a5 to your computer and use it in GitHub Desktop.
A example of a UnaryServerInterceptor
// PingCounter is a struct that keeps track of how many Pings that are performed
type PingCounter struct {
Pings int
}
// ServerCount is a gRPC UnaryServerInterceptor that will count number of API calls.
func (pc *PingCounter) ServerCount(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (response interface{}, err error) {
// Append to PingCounts
pc.Pings++
// We want to extract metadata from the incomming context.
// We dont create a new context since we dont wanna overwrite old metadata
meta, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errors.New("could not grab metadata from context")
}
// Set ping-counts into the current ping value
meta.Set("ping-counts", fmt.Sprintf("%d", pc.Pings))
// Metadata is sent on its own, so we need to send the header. There is also something called Trailer
grpc.SendHeader(ctx, meta)
// Last but super important, execute the handler so that the actualy gRPC request is also performed
return handler(ctx, req)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment