Documentation
¶
Overview ¶
Package middleware contains gRPC server and client interceptors that wraps unary and streaming RPCs to provide additional functionality.
This package contains the following middleware:
- Stream Canceler server middleware for canceling streaming requests.
- OpenTelemetry server and client middleware in the otel subpackage.
Example to use the server middleware:
srv := grpc.NewServer(middleware.StreamCanceler())
Example to use the client middleware:
conn, err := grpc.Dial(host,
otel.GRPCClientOption("service"),
)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MetadataValue ¶
MetadataValue returns the first value for the given metadata key if key exists, else returns an empty string.
func StreamCanceler ¶
func StreamCanceler(ctx context.Context) grpc.StreamServerInterceptor
StreamCanceler provides a middleware that can be used to gracefully stop streaming requests. To stop streaming requests, simply pass in a context with cancellation and cancel the context. When the context given to the StreamCanceler is canceled, it does the following:
- Stops accepting further streaming requests and returns the code Unavailable with message "server is stopping".
- Cancels the context of all streaming requests. Your request handler should obey to the cancelation of request context.
Example:
var (
ctxCancel context.Context
cancelFunc context.CancelFunc
)
ctxCancel, cancelFunc = context.WithCancel(parentCtx)
streamInterceptor := StreamCanceler(ctxCancel)
// Use the interceptor in your server and when you need to shutdown
// your server, simply cancel the context given to the StreamCanceler interceptor.
cancelFunc()
// In your application code, look for context cancellation and respond with proper code.
for {
select {
case <-ctx.Done():
return status.Error(codes.Canceled, "canceled")
...
Types ¶
type WrappedServerStream ¶
type WrappedServerStream struct {
grpc.ServerStream
// contains filtered or unexported fields
}
WrappedServerStream overrides the Context() method of the grpc.ServerStream interface.
func NewWrappedServerStream ¶
func NewWrappedServerStream(ctx context.Context, ss grpc.ServerStream) *WrappedServerStream
NewWrappedServerStream returns a new wrapped grpc ServerStream.
func (*WrappedServerStream) Context ¶
func (w *WrappedServerStream) Context() context.Context
Context returns the context for the server stream.