Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

grpc

v1.85.0
google.golang.org/grpc

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

265 matches

Top ↑

Package grpc implements an RPC system called gRPC.

See grpc.io for more information about gRPC.

Constants

SupportPackageIsVersion3 (7 declarations)

const (
	SupportPackageIsVersion3 = true
	SupportPackageIsVersion4 = true
	SupportPackageIsVersion5 = true
	SupportPackageIsVersion6 = true
	SupportPackageIsVersion7 = true
	SupportPackageIsVersion8 = true
	SupportPackageIsVersion9 = true
)

The SupportPackageIsVersion variables are referenced from generated protocol buffer files to ensure compatibility with the gRPC version used. The latest support package version is 9.

Older versions are kept for compatibility.

These constants should not be referenced from any other code.

Version

const Version = "1.85.0"

Version is the current grpc version.

Variables

ErrClientConnClosing (2 declarations)

var (
	// ErrClientConnClosing indicates that the operation is illegal because
	// the ClientConn is closing.
	//
	// Deprecated: this error should not be relied upon by users; use the status
	// code of Canceled instead.
	ErrClientConnClosing = status.Error(codes.Canceled, "grpc: the client connection is closing")

	// PickFirstBalancerName is the name of the pick_first balancer.
	PickFirstBalancerName = pickfirst.Name
)

DefaultBackoffConfig

var DefaultBackoffConfig = BackoffConfig{
	MaxDelay: 120 * time.Second,
}

DefaultBackoffConfig uses values specified for backoff in https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.

Deprecated: use ConnectParams instead. Will be supported throughout 1.x.

EnableTracing

var EnableTracing bool

EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package. This should only be set before any RPCs are sent or received by this program.

ErrClientConnTimeout

var ErrClientConnTimeout = errors.New("grpc: timed out when dialing")

ErrClientConnTimeout indicates that the ClientConn cannot establish the underlying connections within the specified timeout.

Deprecated: This error is never returned by grpc and should not be referenced by users.

ErrServerStopped

var ErrServerStopped = errors.New("grpc: the server has been stopped")

ErrServerStopped indicates that the operation is now illegal because of the server being stopped.

Functions

ClientSupportedCompressors

func ClientSupportedCompressors(ctx context.Context) ([]string, error)

ClientSupportedCompressors returns compressor names advertised by the client via grpc-accept-encoding header.

The context provided must be the context passed to the server's handler.

Experimental

Notice: This function is EXPERIMENTAL and may be changed or removed in a later release.

Code

func Code(err error) codes.Code

Code returns the error code for err if it was produced by the rpc system. Otherwise, it returns codes.Unknown.

Deprecated: use status.Code instead.

ErrorDesc

func ErrorDesc(err error) string

ErrorDesc returns the error description of err if it was produced by the rpc system. Otherwise, it returns err.Error() or empty string when err is nil.

Deprecated: use status.Convert and Message method instead.

Errorf

func Errorf(c codes.Code, format string, a ...any) error

Errorf returns an error containing an error code and a description; Errorf returns nil if c is OK.

Deprecated: use status.Errorf instead.

Invoke

func Invoke(ctx context.Context, method string, args, reply any, cc *ClientConn, opts ...CallOption) error

Invoke sends the RPC request on the wire and returns after response is received. This is typically called by generated code.

DEPRECATED: Use ClientConn.Invoke instead.

Method

func Method(ctx context.Context) (string, bool)

Method returns the method string for the server context. The returned string is in the format of "/service/method".

MethodFromServerStream

func MethodFromServerStream(stream ServerStream) (string, bool)

MethodFromServerStream returns the method string for the input stream. The returned string is in the format of "/service/method".

NewContextWithServerTransportStream

func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context

NewContextWithServerTransportStream creates a new context from ctx and attaches stream to it.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

SendHeader

func SendHeader(ctx context.Context, md metadata.MD) error

SendHeader sends header metadata. It may be called at most once, and may not be called after any event that causes headers to be sent (see SetHeader for a complete list). The provided md and headers set by SetHeader() will be sent.

The error returned is compatible with the status package. However, the status code will often not match the RPC status as seen by the client application, and therefore, should not be relied upon for this purpose.

SetHeader

func SetHeader(ctx context.Context, md metadata.MD) error

SetHeader sets the header metadata to be sent from the server to the client. The context provided must be the context passed to the server's handler.

Streaming RPCs should prefer the SetHeader method of the ServerStream.

When called multiple times, all the provided metadata will be merged. All the metadata will be sent out when one of the following happens:

  • grpc.SendHeader is called, or for streaming handlers, stream.SendHeader.
  • The first response message is sent. For unary handlers, this occurs when the handler returns; for streaming handlers, this can happen when stream's SendMsg method is called.
  • An RPC status is sent out (error or success). This occurs when the handler returns.

SetHeader will fail if called after any of the events above.

The error returned is compatible with the status package. However, the status code will often not match the RPC status as seen by the client application, and therefore, should not be relied upon for this purpose.

SetSendCompressor

func SetSendCompressor(ctx context.Context, name string) error

SetSendCompressor sets a compressor for outbound messages from the server. It must not be called after any event that causes headers to be sent (see ServerStream.SetHeader for the complete list). Provided compressor is used when below conditions are met:

  • compressor is registered via encoding.RegisterCompressor
  • compressor name must exist in the client advertised compressor names sent in grpc-accept-encoding header. Use ClientSupportedCompressors to get client supported compressor names.

The context provided must be the context passed to the server's handler. It must be noted that compressor name encoding.Identity disables the outbound compression. By default, server messages will be sent using the same compressor with which request messages were sent.

It is not safe to call SetSendCompressor concurrently with SendHeader and SendMsg.

Experimental

Notice: This function is EXPERIMENTAL and may be changed or removed in a later release.

SetTrailer

func SetTrailer(ctx context.Context, md metadata.MD) error

SetTrailer sets the trailer metadata that will be sent when an RPC returns. When called more than once, all the provided metadata will be merged.

The error returned is compatible with the status package. However, the status code will often not match the RPC status as seen by the client application, and therefore, should not be relied upon for this purpose.

Types

AuthorityOverrideCallOption

type AuthorityOverrideCallOption struct {
	Authority string
}

AuthorityOverrideCallOption is a CallOption that indicates the HTTP/2 :authority header value to use for the call.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

BackoffConfig

type BackoffConfig struct {
	// MaxDelay is the upper bound of backoff delay.
	MaxDelay time.Duration
}

BackoffConfig defines the parameters for the default gRPC backoff strategy.

Deprecated: use ConnectParams instead. Will be supported throughout 1.x.

BidiStreamingClient

type BidiStreamingClient[Req any, Res any] interface {
	// Send sends a request message to the server.  The client may call Send
	// multiple times to send multiple messages to the server.  On error, Send
	// aborts the stream.  If the error was generated by the client, the status
	// is returned directly.  Otherwise, io.EOF is returned, and the status of
	// the stream may be discovered using Recv().
	Send(*Req) error

	// Recv receives the next response message from the server. The client may
	// repeatedly call Recv to read messages from the response stream.  If
	// io.EOF is returned, the stream has terminated with an OK status.  Any
	// other error is compatible with the status package and indicates the
	// RPC's status code and message.
	Recv() (*Res, error)

	// ClientStream is embedded to provide Context, Header, Trailer, and
	// CloseSend functionality.  No other methods in the ClientStream should be
	// called directly.
	ClientStream
}

BidiStreamingClient represents the client side of a bidirectional-streaming (many requests, many responses) RPC. It is generic over both the type of the request message stream and the type of the response message stream. It is used in generated code.

BidiStreamingServer

type BidiStreamingServer[Req any, Res any] interface {
	// Recv receives the next request message from the client.  The server may
	// repeatedly call Recv to read messages from the request stream.  If
	// io.EOF is returned, it indicates the client called CloseSend on its
	// BidiStreamingClient.  Any other error indicates the stream was
	// terminated unexpectedly, and the handler method should return, as the
	// stream is no longer usable.
	Recv() (*Req, error)

	// Send sends a response message to the client.  The server handler may
	// call Send multiple times to send multiple messages to the client.  An
	// error is returned if the stream was terminated unexpectedly, and the
	// handler method should return, as the stream is no longer usable.
	Send(*Res) error

	// ServerStream is embedded to provide Context, SetHeader, SendHeader, and
	// SetTrailer functionality.  No other methods in the ServerStream should
	// be called directly.
	ServerStream
}

BidiStreamingServer represents the server side of a bidirectional-streaming (many requests, many responses) RPC. It is generic over both the type of the request message stream and the type of the response message stream. It is used in generated code.

To terminate the stream, return from the handler method and return an error from the status package, or use nil to indicate an OK status code.

CallOption

type CallOption interface {
	// contains filtered or unexported methods
}

CallOption configures a Call before it starts or extracts information from a Call after it completes.

CallAuthority

func CallAuthority(authority string) CallOption

CallAuthority returns a CallOption that sets the HTTP/2 :authority header of an RPC to the specified value. When using CallAuthority, the credentials in use must implement the AuthorityValidator interface.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

CallContentSubtype

func CallContentSubtype(contentSubtype string) CallOption

CallContentSubtype returns a CallOption that will set the content-subtype for a call. For example, if content-subtype is "json", the Content-Type over the wire will be "application/grpc+json". The content-subtype is converted to lowercase before being included in Content-Type. See Content-Type on https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for more details.

If ForceCodec is not also used, the content-subtype will be used to look up the Codec to use in the registry controlled by RegisterCodec. See the documentation on RegisterCodec for details on registration. The lookup of content-subtype is case-insensitive. If no such Codec is found, the call will result in an error with code codes.Internal.

If ForceCodec is also used, that Codec will be used for all request and response messages, with the content-subtype set to the given contentSubtype here for requests.

CallCustomCodec

func CallCustomCodec(codec Codec) CallOption

CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of an encoding.Codec.

Deprecated: use ForceCodec instead.

FailFast

func FailFast(failFast bool) CallOption

FailFast is the opposite of WaitForReady.

Deprecated: use WaitForReady.

ForceCodec

func ForceCodec(codec encoding.Codec) CallOption

ForceCodec returns a CallOption that will set codec to be used for all request and response messages for a call. The result of calling Name() will be used as the content-subtype after converting to lowercase, unless CallContentSubtype is also used.

See Content-Type on https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for more details. Also see the documentation on RegisterCodec and CallContentSubtype for more details on the interaction between Codec and content-subtype.

This function is provided for advanced users; prefer to use only CallContentSubtype to select a registered codec instead.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

ForceCodecV2

func ForceCodecV2(codec encoding.CodecV2) CallOption

ForceCodecV2 returns a CallOption that will set codec to be used for all request and response messages for a call. The result of calling Name() will be used as the content-subtype after converting to lowercase, unless CallContentSubtype is also used.

See Content-Type on https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for more details. Also see the documentation on RegisterCodec and CallContentSubtype for more details on the interaction between Codec and content-subtype.

This function is provided for advanced users; prefer to use only CallContentSubtype to select a registered codec instead.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

Header

func Header(md *metadata.MD) CallOption

Header returns a CallOptions that retrieves the header metadata for a unary RPC.

MaxCallRecvMsgSize

func MaxCallRecvMsgSize(bytes int) CallOption

MaxCallRecvMsgSize returns a CallOption which sets the maximum message size in bytes the client can receive. If this is not set, gRPC uses the default 4MB.

MaxCallSendMsgSize

func MaxCallSendMsgSize(bytes int) CallOption

MaxCallSendMsgSize returns a CallOption which sets the maximum message size in bytes the client can send. If this is not set, gRPC uses the default `math.MaxInt32`.

MaxRetryRPCBufferSize

func MaxRetryRPCBufferSize(bytes int) CallOption

MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory used for buffering this RPC's requests for retry purposes.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

OnFinish

func OnFinish(onFinish func(err error)) CallOption

OnFinish returns a CallOption that configures a callback to be called when the call completes. The error passed to the callback is the status of the RPC, and may be nil. The onFinish callback provided will only be called once by gRPC. This is mainly used to be used by streaming interceptors, to be notified when the RPC completes along with information about the status of the RPC.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

Peer

func Peer(p *peer.Peer) CallOption

Peer returns a CallOption that retrieves peer information for a unary RPC. The peer field will be populated *after* the RPC completes.

PerRPCCredentials

func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption

PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials for a call.

StaticMethod

func StaticMethod() CallOption

StaticMethod returns a CallOption which specifies that a call is being made to a method that is static, which means the method is known at compile time and doesn't change at runtime. This can be used as a signal to stats plugins that this method is safe to include as a key to a measurement.

Trailer

func Trailer(md *metadata.MD) CallOption

Trailer returns a CallOptions that retrieves the trailer metadata for a unary RPC.

UseCompressor

func UseCompressor(name string) CallOption

UseCompressor returns a CallOption which sets the compressor used when sending the request. If WithCompressor is also set, UseCompressor has higher priority.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

WaitForReady

func WaitForReady(waitForReady bool) CallOption

WaitForReady configures the RPC's behavior when the client is in TRANSIENT_FAILURE, which occurs when all addresses fail to connect. If waitForReady is false, the RPC will fail immediately. Otherwise, the client will wait until a connection becomes available or the RPC's deadline is reached.

By default, RPCs do not "wait for ready".

ClientConn

type ClientConn struct {
	// contains filtered or unexported fields
}

ClientConn represents a virtual connection to a conceptual endpoint, to perform RPCs.

A ClientConn is free to have zero or more actual connections to the endpoint based on configuration, load, etc. It is also free to determine which actual endpoints to use and may change it every RPC, permitting client-side load balancing.

A ClientConn encapsulates a range of functionality including name resolution, TCP connection establishment (with retries and backoff) and TLS handshakes. It also handles errors on established connections by re-resolving the name and reconnecting.

Dial

func Dial(target string, opts ...DialOption) (*ClientConn, error)

Dial calls DialContext(context.Background(), target, opts...).

Deprecated: use NewClient instead. Will be supported throughout 1.x.

DialContext

func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error)

DialContext calls NewClient and then exits idle mode. If WithBlock(true) is used, it calls Connect and WaitForStateChange until either the context expires or the state of the ClientConn is Ready.

One subtle difference between NewClient and Dial and DialContext is that the former uses "dns" as the default name resolver, while the latter use "passthrough" for backward compatibility. This distinction should not matter to most users, but could matter to legacy users that specify a custom dialer and expect it to receive the target string directly.

Deprecated: use NewClient instead. Will be supported throughout 1.x.

NewClient

func NewClient(target string, opts ...DialOption) (conn *ClientConn, err error)

NewClient creates a new gRPC "channel" for the target URI provided. No I/O is performed. Use of the ClientConn for RPCs will automatically cause it to connect. The Connect method may be called to manually create a connection, but for most users this should be unnecessary.

The target name syntax is defined in https://github.com/grpc/grpc/blob/master/doc/naming.md. E.g. to use the dns name resolver, a "dns:///" prefix may be applied to the target. The default name resolver will be used if no scheme is detected, or if the parsed scheme is not a registered name resolver. The default resolver is "dns" but can be overridden using the resolver package's SetDefaultScheme.

Examples:

  • "foo.googleapis.com:8080"
  • "dns:///foo.googleapis.com:8080"
  • "dns:///foo.googleapis.com"
  • "dns:///10.0.0.213:8080"
  • "dns:///%5B2001:db8:85a3:8d3:1319:8a2e:370:7348%5D:443"
  • "dns://8.8.8.8/foo.googleapis.com:8080"
  • "dns://8.8.8.8/foo.googleapis.com"
  • "zookeeper://zk.example.com:9900/example_service"

The DialOptions returned by WithBlock, WithTimeout, WithReturnConnectionError, and FailOnNonTempDialError are ignored by this function.

ClientConn.CanonicalTarget

func (cc *ClientConn) CanonicalTarget() string

CanonicalTarget returns the canonical target string used when creating cc.

This always has the form "<scheme>://[authority]/<endpoint>". For example:

  • "dns:///example.com:42"
  • "dns://8.8.8.8/example.com:42"
  • "unix:///path/to/socket"

ClientConn.Close

func (cc *ClientConn) Close() error

Close tears down the ClientConn and all underlying connections.

ClientConn.Connect

func (cc *ClientConn) Connect()

Connect causes all subchannels in the ClientConn to attempt to connect if the channel is idle. Does not wait for the connection attempts to begin before returning.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

ClientConn.GetMethodConfig

func (cc *ClientConn) GetMethodConfig(method string) MethodConfig

GetMethodConfig gets the method config of the input method. If there's an exact match for input method (i.e. /service/method), we return the corresponding MethodConfig. If there isn't an exact match for the input method, we look for the service's default config under the service (i.e /service/) and then for the default for all services (empty string).

If there is a default MethodConfig for the service, we return it. Otherwise, we return an empty MethodConfig.

ClientConn.GetState

func (cc *ClientConn) GetState() connectivity.State

GetState returns the connectivity.State of ClientConn.

ClientConn.Invoke

func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply any, opts ...CallOption) error

Invoke sends the RPC request on the wire and returns after response is received. This is typically called by generated code.

All errors returned by Invoke are compatible with the status package.

ClientConn.NewStream

func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)

NewStream creates a new Stream for the client side. This is typically called by generated code. ctx is used for the lifetime of the stream.

To ensure resources are not leaked due to the stream returned, one of the following actions must be performed:

  1. Call Close on the ClientConn.
  2. Cancel the context provided.
  3. Call RecvMsg until a non-nil error is returned. A protobuf-generated client-streaming RPC, for instance, might use the helper function CloseAndRecv (note that CloseSend does not Recv, therefore is not guaranteed to release all resources).
  4. Receive a non-nil, non-io.EOF error from Header or SendMsg.

If none of the above happen, a goroutine and a context will be leaked, and grpc will not call the optionally-configured stats handler with a stats.End message.

ClientConn.ResetConnectBackoff

func (cc *ClientConn) ResetConnectBackoff()

ResetConnectBackoff wakes up all subchannels in transient failure and causes them to attempt another connection immediately. It also resets the backoff times used for subsequent attempts regardless of the current state.

In general, this function should not be used. Typical service or network outages result in a reasonable client reconnection strategy by default. However, if a previously unavailable network becomes available, this may be used to trigger an immediate reconnect.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

ClientConn.Target

func (cc *ClientConn) Target() string

Target returns the target string of the ClientConn.

ClientConn.WaitForStateChange

func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool

WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or ctx expires. A true value is returned in former case and false in latter.

ClientConnInterface

type ClientConnInterface interface {
	// Invoke performs a unary RPC and returns after the response is received
	// into reply.
	Invoke(ctx context.Context, method string, args any, reply any, opts ...CallOption) error
	// NewStream begins a streaming RPC.
	NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
}

ClientConnInterface defines the functions clients need to perform unary and streaming RPCs. It is implemented by *ClientConn, and is only intended to be referenced by generated code.

ClientStream

type ClientStream interface {
	// Header returns the header metadata received from the server if there
	// is any. It blocks if the metadata is not ready to read.  If the metadata
	// is nil and the error is also nil, then the stream was terminated without
	// headers, and the status can be discovered by calling RecvMsg.
	Header() (metadata.MD, error)
	// Trailer returns the trailer metadata from the server, if there is any.
	// It must only be called after stream.CloseAndRecv has returned, or
	// stream.Recv has returned a non-nil error (including io.EOF).
	Trailer() metadata.MD
	// CloseSend closes the send direction of the stream. This method always
	// returns a nil error. The status of the stream may be discovered using
	// RecvMsg. It is also not safe to call CloseSend concurrently with SendMsg.
	CloseSend() error
	// Context returns the context for this stream.
	//
	// It should not be called until after Header or RecvMsg has returned. Once
	// called, subsequent client-side retries are disabled.
	Context() context.Context
	// SendMsg is generally called by generated code. On error, SendMsg aborts
	// the stream. If the error was generated by the client, the status is
	// returned directly; otherwise, io.EOF is returned and the status of
	// the stream may be discovered using RecvMsg. For unary or server-streaming
	// RPCs (StreamDesc.ClientStreams is false), a nil error is returned
	// unconditionally.
	//
	// SendMsg blocks until:
	//   - There is sufficient flow control to schedule m with the transport, or
	//   - The stream is done, or
	//   - The stream breaks.
	//
	// SendMsg does not wait until the message is received by the server. An
	// untimely stream closure may result in lost messages. To ensure delivery,
	// users should ensure the RPC completed successfully using RecvMsg.
	//
	// It is safe to have a goroutine calling SendMsg and another goroutine
	// calling RecvMsg on the same stream at the same time, but it is not safe
	// to call SendMsg on the same stream in different goroutines. It is also
	// not safe to call CloseSend concurrently with SendMsg.
	//
	// It is not safe to modify the message after calling SendMsg. Tracing
	// libraries and stats handlers may use the message lazily.
	SendMsg(m any) error
	// RecvMsg blocks until it receives a message into m or the stream is
	// done. It returns io.EOF when the stream completes successfully. On
	// any other error, the stream is aborted and the error contains the RPC
	// status.
	//
	// It is safe to have a goroutine calling SendMsg and another goroutine
	// calling RecvMsg on the same stream at the same time, but it is not
	// safe to call RecvMsg on the same stream in different goroutines.
	RecvMsg(m any) error
}

ClientStream defines the client-side behavior of a streaming RPC.

All errors returned from ClientStream methods are compatible with the status package.

NewClientStream

func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)

NewClientStream is a wrapper for ClientConn.NewStream.

ClientStreamingClient

type ClientStreamingClient[Req any, Res any] interface {
	// Send sends a request message to the server.  The client may call Send
	// multiple times to send multiple messages to the server.  On error, Send
	// aborts the stream.  If the error was generated by the client, the status
	// is returned directly.  Otherwise, io.EOF is returned, and the status of
	// the stream may be discovered using CloseAndRecv().
	Send(*Req) error

	// CloseAndRecv closes the request stream and waits for the server's
	// response.  This method must be called once and only once after sending
	// all request messages.  Any error returned is implemented by the status
	// package.
	CloseAndRecv() (*Res, error)

	// ClientStream is embedded to provide Context, Header, and Trailer
	// functionality.  No other methods in the ClientStream should be called
	// directly.
	ClientStream
}

ClientStreamingClient represents the client side of a client-streaming (many requests, one response) RPC. It is generic over both the type of the request message stream and the type of the unary response message. It is used in generated code.

ClientStreamingServer

type ClientStreamingServer[Req any, Res any] interface {
	// Recv receives the next request message from the client.  The server may
	// repeatedly call Recv to read messages from the request stream.  If
	// io.EOF is returned, it indicates the client called CloseAndRecv on its
	// ClientStreamingClient.  Any other error indicates the stream was
	// terminated unexpectedly, and the handler method should return, as the
	// stream is no longer usable.
	Recv() (*Req, error)

	// SendAndClose sends a single response message to the client and closes
	// the stream.  This method must be called once and only once after all
	// request messages have been processed.  Recv should not be called after
	// calling SendAndClose.
	SendAndClose(*Res) error

	// ServerStream is embedded to provide Context, SetHeader, SendHeader, and
	// SetTrailer functionality.  No other methods in the ServerStream should
	// be called directly.
	ServerStream
}

ClientStreamingServer represents the server side of a client-streaming (many requests, one response) RPC. It is generic over both the type of the request message stream and the type of the unary response message. It is used in generated code.

To terminate the RPC, call SendAndClose and return nil from the method handler or do not call SendAndClose and return an error from the status package.

Codec

type Codec interface {
	// Marshal returns the wire format of v.
	Marshal(v any) ([]byte, error)
	// Unmarshal parses the wire format into v.
	Unmarshal(data []byte, v any) error
	// String returns the name of the Codec implementation.  This is unused by
	// gRPC.
	String() string
}

Codec defines the interface gRPC uses to encode and decode messages. Note that implementations of this interface must be thread safe; a Codec's methods can be called from concurrent goroutines.

Deprecated: use encoding.Codec instead.

Compressor

type Compressor interface {
	// Do compresses p into w.
	Do(w io.Writer, p []byte) error
	// Type returns the compression algorithm the Compressor uses.
	Type() string
}

Compressor defines the interface gRPC uses to compress a message.

Deprecated: use package encoding.

NewGZIPCompressor

func NewGZIPCompressor() Compressor

NewGZIPCompressor creates a Compressor based on GZIP.

Deprecated: use package encoding/gzip.

NewGZIPCompressorWithLevel

func NewGZIPCompressorWithLevel(level int) (Compressor, error)

NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead of assuming DefaultCompression.

The error returned will be nil if the level is valid.

Deprecated: use package encoding/gzip.

CompressorCallOption

type CompressorCallOption struct {
	CompressorType string
}

CompressorCallOption is a CallOption that indicates the compressor to use.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

ConnectParams

type ConnectParams struct {
	// Backoff specifies the configuration options for connection backoff.
	Backoff backoff.Config
	// MinConnectTimeout is the minimum amount of time we are willing to give a
	// connection to complete.
	MinConnectTimeout time.Duration
}

ConnectParams defines the parameters for connecting and retrying. Users are encouraged to use this instead of the BackoffConfig type defined above. See here for more details: https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

ContentSubtypeCallOption

type ContentSubtypeCallOption struct {
	ContentSubtype string
}

ContentSubtypeCallOption is a CallOption that indicates the content-subtype used for marshaling messages.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

CustomCodecCallOption

type CustomCodecCallOption struct {
	Codec Codec
}

CustomCodecCallOption is a CallOption that indicates the codec used for marshaling messages.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

Decompressor

type Decompressor interface {
	// Do reads the data from r and uncompress them.
	Do(r io.Reader) ([]byte, error)
	// Type returns the compression algorithm the Decompressor uses.
	Type() string
}

Decompressor defines the interface gRPC uses to decompress a message.

Deprecated: use package encoding.

NewGZIPDecompressor

func NewGZIPDecompressor() Decompressor

NewGZIPDecompressor creates a Decompressor based on GZIP.

Deprecated: use package encoding/gzip.

DialOption

type DialOption interface {
	// contains filtered or unexported methods
}

DialOption configures how we set up the connection.

FailOnNonTempDialError

func FailOnNonTempDialError(f bool) DialOption

FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on non-temporary dial errors. If f is true, and dialer returns a non-temporary error, gRPC will fail the connection to the network address and won't try to reconnect. The default value of FailOnNonTempDialError is false.

FailOnNonTempDialError only affects the initial dial, and does not do anything useful unless you are also using WithBlock().

Use of this feature is not recommended. For more information, please see: https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md

Deprecated: this DialOption is not supported by NewClient. This API may be changed or removed in a later release.

WithAuthority

func WithAuthority(a string) DialOption

WithAuthority returns a DialOption that specifies the value to be used as the :authority pseudo-header and as the server name in authentication handshake. This overrides all other ways of setting authority on the channel, but can be overridden per-call by using grpc.CallAuthority.

WithBackoffConfig

func WithBackoffConfig(b BackoffConfig) DialOption

WithBackoffConfig configures the dialer to use the provided backoff parameters after connection failures.

Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.

WithBackoffMaxDelay

func WithBackoffMaxDelay(md time.Duration) DialOption

WithBackoffMaxDelay configures the dialer to use the provided maximum delay when backing off after failed connection attempts.

Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.

WithBlock

func WithBlock() DialOption

WithBlock returns a DialOption which makes callers of Dial block until the underlying connection is up. Without this, Dial returns immediately and connecting the server happens in background.

Use of this feature is not recommended. For more information, please see: https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md

Deprecated: this DialOption is not supported by NewClient. Will be supported throughout 1.x.

WithChainStreamInterceptor

func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption

WithChainStreamInterceptor returns a DialOption that specifies the chained interceptor for streaming RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All interceptors added by this method will be chained, and the interceptor defined by WithStreamInterceptor will always be prepended to the chain.

WithChainUnaryInterceptor

func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption

WithChainUnaryInterceptor returns a DialOption that specifies the chained interceptor for unary RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All interceptors added by this method will be chained, and the interceptor defined by WithUnaryInterceptor will always be prepended to the chain.

WithChannelzParentID

func WithChannelzParentID(c channelz.Identifier) DialOption

WithChannelzParentID returns a DialOption that specifies the channelz ID of current ClientConn's parent. This function is used in nested channel creation (e.g. grpclb dial).

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

WithCodec

func WithCodec(c Codec) DialOption

WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.

Deprecated: use WithDefaultCallOptions(ForceCodec(_)) instead. Will be supported throughout 1.x.

WithCompressor

func WithCompressor(cp Compressor) DialOption

WithCompressor returns a DialOption which sets a Compressor to use for message compression. It has lower priority than the compressor set by the UseCompressor CallOption.

Deprecated: use UseCompressor instead. Will be supported throughout 1.x.

WithConnectParams

func WithConnectParams(p ConnectParams) DialOption

WithConnectParams configures the ClientConn to use the provided ConnectParams for creating and maintaining connections to servers.

The backoff configuration specified as part of the ConnectParams overrides all defaults specified in https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Consider using the backoff.DefaultConfig as a base, in cases where you want to override only a subset of the backoff configuration.

WithContextDialer

func WithContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption

WithContextDialer returns a DialOption that sets a dialer to create connections. If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's Temporary() method to decide if it should try to reconnect to the network address.

Note that gRPC by default performs name resolution on the target passed to NewClient. To bypass name resolution and cause the target string to be passed directly to the dialer here instead, use the "passthrough" resolver by specifying it in the target string, e.g. "passthrough:target".

Note: All supported releases of Go (as of December 2023) override the OS defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive with OS defaults for keepalive time and interval, use a net.Dialer that sets the KeepAlive field to a negative value, and sets the SO_KEEPALIVE socket option to true from the Control field. For a concrete example of how to do this, see internal.NetDialerWithTCPKeepalive().

For more information, please see issue 23459 in the Go GitHub repo.

WithCredentialsBundle

func WithCredentialsBundle(b credentials.Bundle) DialOption

WithCredentialsBundle returns a DialOption to set a credentials bundle for the ClientConn.WithCreds. This should not be used together with WithTransportCredentials.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

WithDecompressor

func WithDecompressor(dc Decompressor) DialOption

WithDecompressor returns a DialOption which sets a Decompressor to use for incoming message decompression. If incoming response messages are encoded using the decompressor's Type(), it will be used. Otherwise, the message encoding will be used to look up the compressor registered via encoding.RegisterCompressor, which will then be used to decompress the message. If no compressor is registered for the encoding, an Unimplemented status error will be returned.

Deprecated: use encoding.RegisterCompressor instead. Will be supported throughout 1.x.

WithDefaultCallOptions

func WithDefaultCallOptions(cos ...CallOption) DialOption

WithDefaultCallOptions returns a DialOption which sets the default CallOptions for calls over the connection.

WithDefaultServiceConfig

func WithDefaultServiceConfig(s string) DialOption

WithDefaultServiceConfig returns a DialOption that configures the default service config, which will be used in cases where:

1. WithDisableServiceConfig is also used, or

2. The name resolver does not provide a service config or provides an invalid service config.

The parameter s is the JSON representation of the default service config. For more information about service configs, see: https://github.com/grpc/grpc/blob/master/doc/service_config.md For a simple example of usage, see: examples/features/load_balancing/client/main.go

WithDialer

func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption

WithDialer returns a DialOption that specifies a function to use for dialing network addresses. If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's Temporary() method to decide if it should try to reconnect to the network address.

Deprecated: use WithContextDialer instead. Will be supported throughout 1.x.

WithDisableHealthCheck

func WithDisableHealthCheck() DialOption

WithDisableHealthCheck disables the LB channel health checking for all SubConns of this ClientConn.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

WithDisableRetry

func WithDisableRetry() DialOption

WithDisableRetry returns a DialOption that disables retries, even if the service config enables them. This does not impact transparent retries, which will happen automatically if no data is written to the wire or if the RPC is unprocessed by the remote server.

WithDisableServiceConfig

func WithDisableServiceConfig() DialOption

WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any service config provided by the resolver and provides a hint to the resolver to not fetch service configs.

Note that this dial option only disables service config from resolver. If default service config is provided, gRPC will use the default service config.

WithIdleTimeout

func WithIdleTimeout(d time.Duration) DialOption

WithIdleTimeout returns a DialOption that configures an idle timeout for the channel. If the channel is idle for the configured timeout, i.e there are no ongoing RPCs and no new RPCs are initiated, the channel will enter idle mode and as a result the name resolver and load balancer will be shut down. The channel will exit idle mode when the Connect() method is called or when an RPC is initiated.

A default timeout of 30 minutes will be used if this dial option is not set at dial time and idleness can be disabled by passing a timeout of zero.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

WithInitialConnWindowSize

func WithInitialConnWindowSize(s int32) DialOption

WithInitialConnWindowSize returns a DialOption which sets the value for initial window size on a connection. The lower bound for window size is 64K and any value smaller than that will be ignored.

WithInitialWindowSize

func WithInitialWindowSize(s int32) DialOption

WithInitialWindowSize returns a DialOption which sets the value for initial window size on a stream. The lower bound for window size is 64K and any value smaller than that will be ignored.

WithInsecure

func WithInsecure() DialOption

WithInsecure returns a DialOption which disables transport security for this ClientConn. Under the hood, it uses insecure.NewCredentials().

Note that using this DialOption with per-RPC credentials (through WithCredentialsBundle or WithPerRPCCredentials) which require transport security is incompatible and will cause RPCs to fail.

Deprecated: use WithTransportCredentials and insecure.NewCredentials() instead. Will be supported throughout 1.x.

WithKeepaliveParams

func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption

WithKeepaliveParams returns a DialOption that specifies keepalive parameters for the client transport.

Keepalive is disabled by default.

WithLocalDNSResolution

func WithLocalDNSResolution() DialOption

WithLocalDNSResolution forces local DNS name resolution even when a proxy is specified in the environment. By default, the server name is provided directly to the proxy as part of the CONNECT handshake. This is ignored if WithNoProxy is used.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

WithMaxCallAttempts

func WithMaxCallAttempts(n int) DialOption

WithMaxCallAttempts returns a DialOption that configures the maximum number of attempts per call (including retries and hedging) using the channel. Service owners may specify a higher value for these parameters, but higher values will be treated as equal to the maximum value by the client implementation. This mitigates security concerns related to the service config being transferred to the client via DNS.

A value of 5 will be used if this dial option is not set or n < 2.

WithMaxHeaderListSize

func WithMaxHeaderListSize(s uint32) DialOption

WithMaxHeaderListSize returns a DialOption that specifies the maximum (uncompressed) size of header list that the client is prepared to accept.

WithMaxMsgSize

func WithMaxMsgSize(s int) DialOption

WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive.

Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. Will be supported throughout 1.x.

WithNoProxy

func WithNoProxy() DialOption

WithNoProxy returns a DialOption which disables the use of proxies for this ClientConn. This is ignored if WithDialer or WithContextDialer are used.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

WithPerRPCCredentials

func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption

WithPerRPCCredentials returns a DialOption which sets credentials and places auth state on each outbound RPC.

WithReadBufferSize

func WithReadBufferSize(s int) DialOption

WithReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most for each read syscall.

The default value for this buffer is 32KB. Zero or negative values will disable read buffer for a connection so data framer can access the underlying conn directly.

WithResolvers

func WithResolvers(rs ...resolver.Builder) DialOption

WithResolvers allows a list of resolver implementations to be registered locally with the ClientConn without needing to be globally registered via resolver.Register. They will be matched against the scheme used for the current Dial only, and will take precedence over the global registry.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

WithReturnConnectionError

func WithReturnConnectionError() DialOption

WithReturnConnectionError returns a DialOption which makes the client connection return a string containing both the last connection error that occurred and the context.DeadlineExceeded error. Implies WithBlock()

Use of this feature is not recommended. For more information, please see: https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md

Deprecated: this DialOption is not supported by NewClient. Will be supported throughout 1.x.

WithSharedWriteBuffer

func WithSharedWriteBuffer(val bool) DialOption

WithSharedWriteBuffer allows reusing per-connection transport write buffer. If this option is set to true every connection will release the buffer after flushing the data on the wire.

Deprecated: shared write buffer is enabled by default. WithSharedWriteBuffer will be removed in a future release.

WithStaticConnWindowSize

func WithStaticConnWindowSize(s int32) DialOption

WithStaticConnWindowSize returns a DialOption which sets the initial connection window size to the value provided and disables dynamic flow control.

Note that this also disables dynamic flow control for individual streams, falling back to a default static connection-level window of 64KB. To explicitly configure the stream-level window size, you must also use the WithStaticStreamWindowSize DialOption.

Most users should not configure static flow control windows unless operating in a memory-constrained environment.

WithStaticStreamWindowSize

func WithStaticStreamWindowSize(s int32) DialOption

WithStaticStreamWindowSize returns a DialOption which sets the initial stream window size to the value provided and disables dynamic flow control.

Note that this also disables dynamic flow control for the connection, falling back to a default static connection-level window of 64KB. To use a larger connection-level window, you must also use the WithStaticConnWindowSize DialOption.

Most users should not configure static flow control windows unless operating in a memory-constrained environment.

WithStatsHandler

func WithStatsHandler(h stats.Handler) DialOption

WithStatsHandler returns a DialOption that specifies the stats handler for all the RPCs and underlying network connections in this ClientConn.

WithStreamInterceptor

func WithStreamInterceptor(f StreamClientInterceptor) DialOption

WithStreamInterceptor returns a DialOption that specifies the interceptor for streaming RPCs.

WithTimeout

func WithTimeout(d time.Duration) DialOption

WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn initially. This is valid if and only if WithBlock() is present.

Deprecated: this DialOption is not supported by NewClient. Will be supported throughout 1.x.

WithTransportCredentials

func WithTransportCredentials(creds credentials.TransportCredentials) DialOption

WithTransportCredentials returns a DialOption which configures a connection level security credentials (e.g., TLS/SSL). This should not be used together with WithCredentialsBundle.

WithUnaryInterceptor

func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption

WithUnaryInterceptor returns a DialOption that specifies the interceptor for unary RPCs.

WithUserAgent

func WithUserAgent(s string) DialOption

WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.

WithWriteBufferSize

func WithWriteBufferSize(s int) DialOption

WithWriteBufferSize determines how much data can be batched before doing a write on the wire. The default value for this buffer is 32KB.

Zero or negative values will disable the write buffer such that each write will be on underlying connection. Note: A Send call may not directly translate to a write.

EmptyCallOption

type EmptyCallOption struct{}

EmptyCallOption does not alter the Call configuration. It can be embedded in another structure to carry satellite data for use by interceptors.

EmptyDialOption

type EmptyDialOption struct{}

EmptyDialOption does not alter the dial configuration. It can be embedded in another structure to build custom dial options.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

EmptyServerOption

type EmptyServerOption struct{}

EmptyServerOption does not alter the server configuration. It can be embedded in another structure to build custom server options.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

FailFastCallOption

type FailFastCallOption struct {
	FailFast bool
}

FailFastCallOption is a CallOption for indicating whether an RPC should fail fast or not.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

ForceCodecCallOption

type ForceCodecCallOption struct {
	Codec encoding.Codec
}

ForceCodecCallOption is a CallOption that indicates the codec used for marshaling messages.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

ForceCodecV2CallOption

type ForceCodecV2CallOption struct {
	CodecV2 encoding.CodecV2
}

ForceCodecV2CallOption is a CallOption that indicates the codec used for marshaling messages.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

GenericClientStream

type GenericClientStream[Req any, Res any] struct {
	ClientStream
}

GenericClientStream implements the ServerStreamingClient, ClientStreamingClient, and BidiStreamingClient interfaces. It is used in generated code.

GenericClientStream[Req, Res].CloseAndRecv

func (x *GenericClientStream[Req, Res]) CloseAndRecv() (*Res, error)

CloseAndRecv closes the sending side of the stream, then receives the unary response from the server. The type of message which it returns is determined by the Res type parameter of the GenericClientStream receiver.

GenericClientStream[Req, Res].Recv

func (x *GenericClientStream[Req, Res]) Recv() (*Res, error)

Recv reads one message from the stream of responses generated by the server. The type of the message returned is determined by the Res type parameter of the GenericClientStream receiver.

GenericClientStream[Req, Res].Send

func (x *GenericClientStream[Req, Res]) Send(m *Req) error

Send pushes one message into the stream of requests to be consumed by the server. The type of message which can be sent is determined by the Req type parameter of the GenericClientStream receiver.

GenericServerStream

type GenericServerStream[Req any, Res any] struct {
	ServerStream
}

GenericServerStream implements the ServerStreamingServer, ClientStreamingServer, and BidiStreamingServer interfaces. It is used in generated code.

GenericServerStream[Req, Res].Recv

func (x *GenericServerStream[Req, Res]) Recv() (*Req, error)

Recv reads one message from the stream of requests generated by the client. The type of the message returned is determined by the Req type parameter of the clientStreamServer receiver.

GenericServerStream[Req, Res].Send

func (x *GenericServerStream[Req, Res]) Send(m *Res) error

Send pushes one message into the stream of responses to be consumed by the client. The type of message which can be sent is determined by the Res type parameter of the serverStreamServer receiver.

GenericServerStream[Req, Res].SendAndClose

func (x *GenericServerStream[Req, Res]) SendAndClose(m *Res) error

SendAndClose pushes the unary response to the client. The type of message which can be sent is determined by the Res type parameter of the clientStreamServer receiver.

HeaderCallOption

type HeaderCallOption struct {
	HeaderAddr *metadata.MD
}

HeaderCallOption is a CallOption for collecting response header metadata. The metadata field will be populated *after* the RPC completes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

MaxHeaderListSizeDialOption

type MaxHeaderListSizeDialOption struct {
	MaxHeaderListSize uint32
}

MaxHeaderListSizeDialOption is a DialOption that specifies the maximum (uncompressed) size of header list that the client is prepared to accept.

MaxHeaderListSizeServerOption

type MaxHeaderListSizeServerOption struct {
	MaxHeaderListSize uint32
}

MaxHeaderListSizeServerOption is a ServerOption that sets the max (uncompressed) size of header list that the server is prepared to accept.

MaxRecvMsgSizeCallOption

type MaxRecvMsgSizeCallOption struct {
	MaxRecvMsgSize int
}

MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message size in bytes the client can receive.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

MaxRetryRPCBufferSizeCallOption

type MaxRetryRPCBufferSizeCallOption struct {
	MaxRetryRPCBufferSize int
}

MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of memory to be used for caching this RPC for retry purposes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

MaxSendMsgSizeCallOption

type MaxSendMsgSizeCallOption struct {
	MaxSendMsgSize int
}

MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message size in bytes the client can send.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

MethodConfig

type MethodConfig = internalserviceconfig.MethodConfig

MethodConfig defines the configuration recommended by the service providers for a particular method.

Deprecated: Users should not use this struct. Service config should be received through name resolver, as specified here https://github.com/grpc/grpc/blob/master/doc/service_config.md

MethodDesc

type MethodDesc struct {
	MethodName string
	Handler    MethodHandler
}

MethodDesc represents an RPC service's method specification.

MethodHandler

type MethodHandler func(srv any, ctx context.Context, dec func(any) error, interceptor UnaryServerInterceptor) (any, error)

MethodHandler is a function type that processes a unary RPC method call.

MethodInfo

type MethodInfo struct {
	// Name is the method name only, without the service name or package name.
	Name string
	// IsClientStream indicates whether the RPC is a client streaming RPC.
	IsClientStream bool
	// IsServerStream indicates whether the RPC is a server streaming RPC.
	IsServerStream bool
}

MethodInfo contains the information of an RPC including its method name and type.

OnFinishCallOption

type OnFinishCallOption struct {
	OnFinish func(error)
}

OnFinishCallOption is CallOption that indicates a callback to be called when the call completes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

PeerCallOption

type PeerCallOption struct {
	PeerAddr *peer.Peer
}

PeerCallOption is a CallOption for collecting the identity of the remote peer. The peer field will be populated *after* the RPC completes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

PerRPCCredsCallOption

type PerRPCCredsCallOption struct {
	Creds credentials.PerRPCCredentials
}

PerRPCCredsCallOption is a CallOption that indicates the per-RPC credentials to use for the call.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

PreparedMsg

type PreparedMsg struct {
	// contains filtered or unexported fields
}

PreparedMsg is responsible for creating a Marshalled and Compressed object.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

PreparedMsg.Encode

func (p *PreparedMsg) Encode(s Stream, msg any) error

Encode marshalls and compresses the message using the codec and compressor for the stream.

Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a gRPC server to serve RPC requests.

NewServer

func NewServer(opt ...ServerOption) *Server

NewServer creates a gRPC server which has no service registered and has not started to accept requests yet.

Server.GetServiceInfo

func (s *Server) GetServiceInfo() map[string]ServiceInfo

GetServiceInfo returns a map from service names to ServiceInfo. Service names include the package names, in the form of <package>.<service>.

Server.GracefulStop

func (s *Server) GracefulStop()

GracefulStop stops the gRPC server gracefully. It stops the server from accepting new connections and RPCs and blocks until all the pending RPCs are finished.

Server.RegisterService

func (s *Server) RegisterService(sd *ServiceDesc, ss any)

RegisterService registers a service and its implementation to the gRPC server. It is called from the IDL generated code. This must be called before invoking Serve. If ss is non-nil (for legacy code), its type is checked to ensure it implements sd.HandlerType.

Server.Serve

func (s *Server) Serve(lis net.Listener) error

Serve accepts incoming connections on the listener lis, creating a new ServerTransport and service goroutine for each. The service goroutines read gRPC requests and then call the registered handlers to reply to them. Serve returns when lis.Accept fails with fatal errors. lis will be closed when this method returns. Serve will return a non-nil error unless Stop or GracefulStop is called.

Note: All supported releases of Go (as of December 2023) override the OS defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive with OS defaults for keepalive time and interval, callers need to do the following two things:

  • pass a net.Listener created by calling the Listen method on a net.ListenConfig with the `KeepAlive` field set to a negative value. This will result in the Go standard library not overriding OS defaults for TCP keepalive interval and time. But this will also result in the Go standard library not enabling TCP keepalives by default.
  • override the Accept method on the passed in net.Listener and set the SO_KEEPALIVE socket option to enable TCP keepalives, with OS defaults.

Server.ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the Go standard library's http.Handler interface by responding to the gRPC request r, by looking up the requested gRPC method in the gRPC server s.

The provided HTTP request must have arrived on an HTTP/2 connection. When using the Go standard library's server, practically this means that the Request must also have arrived over TLS.

To share one port (such as 443 for https) between gRPC and an existing http.Handler, use a root http.Handler such as:

if r.ProtoMajor == 2 && strings.HasPrefix(
	r.Header.Get("Content-Type"), "application/grpc") {
	grpcServer.ServeHTTP(w, r)
} else {
	yourMux.ServeHTTP(w, r)
}

Note that ServeHTTP uses Go's HTTP/2 server implementation which is totally separate from grpc-go's HTTP/2 server. Performance and features may vary between the two paths. ServeHTTP does not support some gRPC features available through grpc-go's HTTP/2 server.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

Server.Stop

func (s *Server) Stop()

Stop stops the gRPC server. It immediately closes all open connections and listeners. It cancels all active RPCs on the server side and the corresponding pending RPCs on the client side will get notified by connection errors.

ServerOption

type ServerOption interface {
	// contains filtered or unexported methods
}

A ServerOption sets options such as credentials, codec and keepalive parameters, etc.

ChainStreamInterceptor

func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption

ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor for streaming RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All stream interceptors added by this method will be chained.

ChainUnaryInterceptor

func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption

ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor for unary RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All unary interceptors added by this method will be chained.

ConnectionTimeout

func ConnectionTimeout(d time.Duration) ServerOption

ConnectionTimeout returns a ServerOption that sets the timeout for connection establishment (up to and including HTTP/2 handshaking) for all new connections. If this is not set, the default is 120 seconds. A zero or negative value will result in an immediate timeout.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

Creds

func Creds(c credentials.TransportCredentials) ServerOption

Creds returns a ServerOption that sets credentials for server connections.

CustomCodec

func CustomCodec(codec Codec) ServerOption

CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.

This will override any lookups by content-subtype for Codecs registered with RegisterCodec.

Deprecated: register codecs using encoding.RegisterCodec. The server will automatically use registered codecs based on the incoming requests' headers. See also https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec. Will be supported throughout 1.x.

ForceServerCodec

func ForceServerCodec(codec encoding.Codec) ServerOption

ForceServerCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.

This will override any lookups by content-subtype for Codecs registered with RegisterCodec.

See Content-Type on https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for more details. Also see the documentation on RegisterCodec and CallContentSubtype for more details on the interaction between encoding.Codec and content-subtype.

This function is provided for advanced users; prefer to register codecs using encoding.RegisterCodec. The server will automatically use registered codecs based on the incoming requests' headers. See also https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec. Will be supported throughout 1.x.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

ForceServerCodecV2

func ForceServerCodecV2(codecV2 encoding.CodecV2) ServerOption

ForceServerCodecV2 is the equivalent of ForceServerCodec, but for the new CodecV2 interface.

Will be supported throughout 1.x.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

HeaderTableSize

func HeaderTableSize(s uint32) ServerOption

HeaderTableSize returns a ServerOption that sets the size of dynamic header table for stream.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

InTapHandle

func InTapHandle(h tap.ServerInHandle) ServerOption

InTapHandle returns a ServerOption that sets the tap handle for all the server transport to be created. Only one can be installed.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

InitialConnWindowSize

func InitialConnWindowSize(s int32) ServerOption

InitialConnWindowSize returns a ServerOption that sets window size for a connection. The lower bound for window size is 64K and any value smaller than that will be ignored.

InitialWindowSize

func InitialWindowSize(s int32) ServerOption

InitialWindowSize returns a ServerOption that sets window size for stream. The lower bound for window size is 64K and any value smaller than that will be ignored.

KeepaliveEnforcementPolicy

func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption

KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server.

KeepaliveParams

func KeepaliveParams(kp keepalive.ServerParameters) ServerOption

KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.

MaxConcurrentStreams

func MaxConcurrentStreams(n uint32) ServerOption

MaxConcurrentStreams returns a ServerOption that will apply a limit on the number of concurrent streams to each ServerTransport.

MaxHeaderListSize

func MaxHeaderListSize(s uint32) ServerOption

MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size of header list that the server is prepared to accept.

MaxMsgSize

func MaxMsgSize(m int) ServerOption

MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive. If this is not set, gRPC uses the default limit.

Deprecated: use MaxRecvMsgSize instead. Will be supported throughout 1.x.

MaxRecvMsgSize

func MaxRecvMsgSize(m int) ServerOption

MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive. If this is not set, gRPC uses the default 4MB.

MaxSendMsgSize

func MaxSendMsgSize(m int) ServerOption

MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send. If this is not set, gRPC uses the default `math.MaxInt32`.

NumStreamWorkers

func NumStreamWorkers(numServerWorkers uint32) ServerOption

NumStreamWorkers returns a ServerOption that sets the number of worker goroutines that should be used to process incoming streams. Setting this to zero (default) will disable workers and spawn a new goroutine for each stream.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

RPCCompressor

func RPCCompressor(cp Compressor) ServerOption

RPCCompressor returns a ServerOption that sets a compressor for outbound messages. For backward compatibility, all outbound messages will be sent using this compressor, regardless of incoming message compression. By default, server messages will be sent using the same compressor with which request messages were sent.

Deprecated: use encoding.RegisterCompressor instead. Will be supported throughout 1.x.

RPCDecompressor

func RPCDecompressor(dc Decompressor) ServerOption

RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages. It has higher priority than decompressors registered via encoding.RegisterCompressor.

Deprecated: use encoding.RegisterCompressor instead. Will be supported throughout 1.x.

ReadBufferSize

func ReadBufferSize(s int) ServerOption

ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most for one read syscall. The default value for this buffer is 32KB. Zero or negative values will disable read buffer for a connection so data framer can access the underlying conn directly.

SharedWriteBuffer

func SharedWriteBuffer(val bool) ServerOption

SharedWriteBuffer allows reusing per-connection transport write buffer. If this option is set to true every connection will release the buffer after flushing the data on the wire.

Deprecated: shared write buffer is enabled by default. SharedWriteBuffer will be removed in a future release.

StaticConnWindowSize

func StaticConnWindowSize(s int32) ServerOption

StaticConnWindowSize returns a ServerOption to set the initial connection window size to the value provided and disables dynamic flow control. The lower bound for window size is 64K and any value smaller than that will be ignored.

Note that this also disables dynamic flow control for individual streams, falling back to a default static connection-level window of 64KB. To explicitly configure the stream-level window size, you must also use the StaticStreamWindowSize ServerOption.

Most users should not configure static flow control windows unless operating in a memory-constrained environment.

StaticStreamWindowSize

func StaticStreamWindowSize(s int32) ServerOption

StaticStreamWindowSize returns a ServerOption to set the initial stream window size to the value provided and disables dynamic flow control. The lower bound for window size is 64K and any value smaller than that will be ignored.

Note that this also disables dynamic flow control for the connection, falling back to a default static connection-level window of 64KB. To use a larger connection-level window, you must also use the StaticConnWindowSize ServerOption.

Most users should not configure static flow control windows unless operating in a memory-constrained environment.

StatsHandler

func StatsHandler(h stats.Handler) ServerOption

StatsHandler returns a ServerOption that sets the stats handler for the server.

StreamInterceptor

func StreamInterceptor(i StreamServerInterceptor) ServerOption

StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the server. Only one stream interceptor can be installed.

UnaryInterceptor

func UnaryInterceptor(i UnaryServerInterceptor) ServerOption

UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the server. Only one unary interceptor can be installed. The construction of multiple interceptors (e.g., chaining) can be implemented at the caller.

UnknownServiceHandler

func UnknownServiceHandler(streamHandler StreamHandler) ServerOption

UnknownServiceHandler returns a ServerOption that allows for adding a custom unknown service handler. The provided method is a bidi-streaming RPC service handler that will be invoked instead of returning the "unimplemented" gRPC error whenever a request is received for an unregistered service or method. The handling function and stream interceptor (if set) have full access to the ServerStream, including its Context.

WaitForHandlers

func WaitForHandlers(w bool) ServerOption

WaitForHandlers cause Stop to wait until all outstanding method handlers have exited before returning. If false, Stop will return as soon as all connections have closed, but method handlers may still be running. By default, Stop does not wait for method handlers to return.

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

WriteBufferSize

func WriteBufferSize(s int) ServerOption

WriteBufferSize determines how much data can be batched before doing a write on the wire. The default value for this buffer is 32KB. Zero or negative values will disable the write buffer such that each write will be on underlying connection. Note: A Send call may not directly translate to a write.

ServerStream

type ServerStream interface {
	// SetHeader sets the header metadata. It may be called multiple times.
	// When call multiple times, all the provided metadata will be merged.
	// All the metadata will be sent out when one of the following happens:
	//  - ServerStream.SendHeader() is called;
	//  - The first response is sent out;
	//  - An RPC status is sent out (error or success).
	SetHeader(metadata.MD) error
	// SendHeader sends the header metadata.
	// The provided md and headers set by SetHeader() will be sent.
	// It fails if called multiple times.
	SendHeader(metadata.MD) error
	// SetTrailer sets the trailer metadata which will be sent with the RPC status.
	// When called more than once, all the provided metadata will be merged.
	SetTrailer(metadata.MD)
	// Context returns the context for this stream.
	Context() context.Context
	// SendMsg sends a message. On error, SendMsg aborts the stream and the
	// error is returned directly.
	//
	// SendMsg blocks until:
	//   - There is sufficient flow control to schedule m with the transport, or
	//   - The stream is done, or
	//   - The stream breaks.
	//
	// SendMsg does not wait until the message is received by the client. An
	// untimely stream closure may result in lost messages.
	//
	// It is safe to have a goroutine calling SendMsg and another goroutine
	// calling RecvMsg on the same stream at the same time, but it is not safe
	// to call SendMsg on the same stream in different goroutines.
	//
	// It is not safe to modify the message after calling SendMsg. Tracing
	// libraries and stats handlers may use the message lazily.
	SendMsg(m any) error
	// RecvMsg blocks until it receives a message into m or the stream is
	// done. It returns io.EOF when the client has performed a CloseSend. On
	// any non-EOF error, the stream is aborted and the error contains the
	// RPC status.
	//
	// It is safe to have a goroutine calling SendMsg and another goroutine
	// calling RecvMsg on the same stream at the same time, but it is not
	// safe to call RecvMsg on the same stream in different goroutines.
	RecvMsg(m any) error
}

ServerStream defines the server-side behavior of a streaming RPC.

Errors returned from ServerStream methods are compatible with the status package. However, the status code will often not match the RPC status as seen by the client application, and therefore, should not be relied upon for this purpose.

ServerStreamingClient

type ServerStreamingClient[Res any] interface {
	// Recv receives the next response message from the server. The client may
	// repeatedly call Recv to read messages from the response stream.  If
	// io.EOF is returned, the stream has terminated with an OK status.  Any
	// other error is compatible with the status package and indicates the
	// RPC's status code and message.
	Recv() (*Res, error)

	// ClientStream is embedded to provide Context, Header, and Trailer
	// functionality.  No other methods in the ClientStream should be called
	// directly.
	ClientStream
}

ServerStreamingClient represents the client side of a server-streaming (one request, many responses) RPC. It is generic over the type of the response message. It is used in generated code.

ServerStreamingServer

type ServerStreamingServer[Res any] interface {
	// Send sends a response message to the client.  The server handler may
	// call Send multiple times to send multiple messages to the client.  An
	// error is returned if the stream was terminated unexpectedly, and the
	// handler method should return, as the stream is no longer usable.
	Send(*Res) error

	// ServerStream is embedded to provide Context, SetHeader, SendHeader, and
	// SetTrailer functionality.  No other methods in the ServerStream should
	// be called directly.
	ServerStream
}

ServerStreamingServer represents the server side of a server-streaming (one request, many responses) RPC. It is generic over the type of the response message. It is used in generated code.

To terminate the response stream, return from the handler method and return an error from the status package, or use nil to indicate an OK status code.

ServerTransportStream

type ServerTransportStream interface {
	Method() string
	SetHeader(md metadata.MD) error
	SendHeader(md metadata.MD) error
	SetTrailer(md metadata.MD) error
}

ServerTransportStream is a minimal interface that a transport stream must implement. This can be used to mock an actual transport stream for tests of handler code that use, for example, grpc.SetHeader (which requires some stream to be in context).

See also NewContextWithServerTransportStream.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

ServerTransportStreamFromContext

func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream

ServerTransportStreamFromContext returns the ServerTransportStream saved in ctx. Returns nil if the given context has no stream associated with it (which implies it is not an RPC invocation context).

Experimental

Notice: This API is EXPERIMENTAL and may be changed or removed in a later release.

ServiceConfig

type ServiceConfig struct {
	serviceconfig.Config

	// Methods contains a map for the methods in this service.  If there is an
	// exact match for a method (i.e. /service/method) in the map, use the
	// corresponding MethodConfig.  If there's no exact match, look for the
	// default config for the service (/service/) and use the corresponding
	// MethodConfig if it exists.  Otherwise, the method has no MethodConfig to
	// use.
	Methods map[string]MethodConfig
	// contains filtered or unexported fields
}

ServiceConfig is provided by the service provider and contains parameters for how clients that connect to the service should behave.

Deprecated: Users should not use this struct. Service config should be received through name resolver, as specified here https://github.com/grpc/grpc/blob/master/doc/service_config.md

ServiceDesc

type ServiceDesc struct {
	ServiceName string
	// The pointer to the service interface. Used to check whether the user
	// provided implementation satisfies the interface requirements.
	HandlerType any
	Methods     []MethodDesc
	Streams     []StreamDesc
	Metadata    any
}

ServiceDesc represents an RPC service's specification.

ServiceInfo

type ServiceInfo struct {
	Methods []MethodInfo
	// Metadata is the metadata specified in ServiceDesc when registering service.
	Metadata any
}

ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service.

ServiceRegistrar

type ServiceRegistrar interface {
	// RegisterService registers a service and its implementation to the
	// concrete type implementing this interface.  It may not be called
	// once the server has started serving.
	// desc describes the service and its methods and handlers. impl is the
	// service implementation which is passed to the method handlers.
	RegisterService(desc *ServiceDesc, impl any)
}

ServiceRegistrar wraps a single method that supports service registration. It enables users to pass concrete types other than grpc.Server to the service registration methods exported by the IDL generated code.

StaticMethodCallOption

type StaticMethodCallOption struct {
	EmptyCallOption
}

StaticMethodCallOption is a CallOption that specifies that a call comes from a static method.

Stream

type Stream interface {
	// Deprecated: See ClientStream and ServerStream documentation instead.
	Context() context.Context
	// Deprecated: See ClientStream and ServerStream documentation instead.
	SendMsg(m any) error
	// Deprecated: See ClientStream and ServerStream documentation instead.
	RecvMsg(m any) error
}

Stream defines the common interface a client or server stream has to satisfy.

Deprecated: See ClientStream and ServerStream documentation instead.

StreamClientInterceptor

type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error)

StreamClientInterceptor intercepts the creation of a ClientStream. Stream interceptors can be specified as a DialOption, using WithStreamInterceptor() or WithChainStreamInterceptor(), when creating a ClientConn. When a stream interceptor(s) is set on the ClientConn, gRPC delegates all stream creations to the interceptor, and it is the responsibility of the interceptor to call streamer.

desc contains a description of the stream. cc is the ClientConn on which the RPC was invoked. streamer is the handler to create a ClientStream and it is the responsibility of the interceptor to call it. opts contain all applicable call options, including defaults from the ClientConn as well as per-call options.

StreamClientInterceptor may return a custom ClientStream to intercept all I/O operations. The returned error must be compatible with the status package.

StreamDesc

type StreamDesc struct {
	// StreamName and Handler are only used when registering handlers on a
	// server.
	StreamName string        // the name of the method excluding the service
	Handler    StreamHandler // the handler called for the method

	// ServerStreams and ClientStreams are used for registering handlers on a
	// server as well as defining RPC behavior when passed to NewClientStream
	// and ClientConn.NewStream.  At least one must be true.
	ServerStreams bool // indicates the server can perform streaming sends
	ClientStreams bool // indicates the client can perform streaming sends
}

StreamDesc represents a streaming RPC service's method specification. Used on the server when registering services and on the client when initiating new streams.

StreamHandler

type StreamHandler func(srv any, stream ServerStream) error

StreamHandler defines the handler called by gRPC server to complete the execution of a streaming RPC. srv is the service implementation on which the RPC was invoked.

If a StreamHandler returns an error, it should either be produced by the status package, or be one of the context errors. Otherwise, gRPC will use codes.Unknown as the status code and err.Error() as the status message of the RPC.

StreamServerInfo

type StreamServerInfo struct {
	// FullMethod is the full RPC method string, i.e., /package.service/method.
	FullMethod string
	// IsClientStream indicates whether the RPC is a client streaming RPC.
	IsClientStream bool
	// IsServerStream indicates whether the RPC is a server streaming RPC.
	IsServerStream bool
}

StreamServerInfo consists of various information about a streaming RPC on server side. All per-rpc information may be mutated by the interceptor.

StreamServerInterceptor

type StreamServerInterceptor func(srv any, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error

StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server.

srv is the service implementation on which the RPC was invoked, and needs to be passed to handler, and not used otherwise. ss is the server side of the stream. info contains all the information of this RPC the interceptor can operate on. And handler is the service method implementation. It is the responsibility of the interceptor to invoke handler to complete the RPC.

Streamer

type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)

Streamer is called by StreamClientInterceptor to create a ClientStream.

TrailerCallOption

type TrailerCallOption struct {
	TrailerAddr *metadata.MD
}

TrailerCallOption is a CallOption for collecting response trailer metadata. The metadata field will be populated *after* the RPC completes.

Experimental

Notice: This type is EXPERIMENTAL and may be changed or removed in a later release.

UnaryClientInterceptor

type UnaryClientInterceptor func(ctx context.Context, method string, req, reply any, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error

UnaryClientInterceptor intercepts the execution of a unary RPC on the client. Unary interceptors can be specified as a DialOption, using WithUnaryInterceptor() or WithChainUnaryInterceptor(), when creating a ClientConn. When a unary interceptor(s) is set on a ClientConn, gRPC delegates all unary RPC invocations to the interceptor, and it is the responsibility of the interceptor to call invoker to complete the processing of the RPC.

method is the RPC name. req and reply are the corresponding request and response messages. cc is the ClientConn on which the RPC was invoked. invoker is the handler to complete the RPC and it is the responsibility of the interceptor to call it. opts contain all applicable call options, including defaults from the ClientConn as well as per-call options.

The returned error must be compatible with the status package.

UnaryHandler

type UnaryHandler func(ctx context.Context, req any) (any, error)

UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal execution of a unary RPC.

If a UnaryHandler returns an error, it should either be produced by the status package, or be one of the context errors. Otherwise, gRPC will use codes.Unknown as the status code and err.Error() as the status message of the RPC.

UnaryInvoker

type UnaryInvoker func(ctx context.Context, method string, req, reply any, cc *ClientConn, opts ...CallOption) error

UnaryInvoker is called by UnaryClientInterceptor to complete RPCs.

UnaryServerInfo

type UnaryServerInfo struct {
	// Server is the service implementation the user provides. This is read-only.
	Server any
	// FullMethod is the full RPC method string, i.e., /package.service/method.
	FullMethod string
}

UnaryServerInfo consists of various information about a unary RPC on server side. All per-rpc information may be mutated by the interceptor.

UnaryServerInterceptor

type UnaryServerInterceptor func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (resp any, err error)

UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info contains all the information of this RPC the interceptor can operate on. And handler is the wrapper of the service method implementation. It is the responsibility of the interceptor to invoke handler to complete the RPC.

Dependency graph