Skip to content

kw510/go-grpc-generics

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go gRPC Generics

CI codecov Go Reference Go Report Card

A generic and uniform interceptor, combining unary and stream gRPC interceptors into a single interceptor.

Just define the interceptor once, then covert into the type gRPC interceptor that you need! 🪄

Insipred by https://github.com/grpc-ecosystem/go-grpc-middleware.

Usage

To use this generic interceptor, first define it, then convert it into a grpc interceptor.

Define an generic Interceptor

We define what the interceptor perfoms before and after the call. This implements the generic interceptor interface.

type YourInterceptor struct {}

func (i YourInterceptor) BeforeHandler(ctx context.Context) context.Context {
  // Performed before the handler is called
  ...
  return ctx // Context is passed into the handler
}

func (i YourInterceptor) AfterHandler(ctx context.Context, err error) {
  // Performed after the handler is called
  ...
}

Using an Interceptor

Pass in the struct to the converter functions, which will return the respective interceptor.

import "github.com/kw510/grpc-interceptor/interceptors"

grpcServer := grpc.NewServer(
  grpc.StreamInterceptor(
    interceptors.StreamServerInterceptor(YourInterceptor{})
  )
  grpc.UnaryInterceptor(
    interceptors.UnaryServerInterceptor(YourInterceptor{})
  )
)