Movatterモバイル変換


[0]ホーム

URL:


grpc

packagemodule
v1.71.0Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 4, 2025 License:Apache-2.0Imports:65Imported by:228,268

Details

Repository

github.com/grpc/grpc-go

Links

README

gRPC-Go

GoDocGoReportCardcodecov

TheGo implementation ofgRPC: A high performance, open source, generalRPC framework that puts mobile and HTTP/2 first. For more information see theGo gRPC docs, or jump directly into thequick start.

Prerequisites

Installation

Simply add the following import to your code, and thengo [build|run|test]will automatically fetch the necessary dependencies:

import "google.golang.org/grpc"

Note: If you are trying to accessgrpc-go fromChina, see theFAQ below.

Learn more

FAQ

I/O Timeout Errors

Thegolang.org domain may be blocked from some countries.go get usuallyproduces an error like the following when this happens:

$ go get -u google.golang.org/grpcpackage google.golang.org/grpc: unrecognized import path "google.golang.org/grpc" (https fetch: Get https://google.golang.org/grpc?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)

To build Go code, there are several options:

  • Set up a VPN and access google.golang.org through that.

  • With Go module support: it is possible to use thereplace feature ofgo mod to create aliases for golang.org packages. In your project's directory:

    go mod edit -replace=google.golang.org/grpc=github.com/grpc/grpc-go@latestgo mod tidygo mod vendorgo build -mod=vendor

    Again, this will need to be done for all transitive dependencies hosted ongolang.org as well. For details, refer togolang/go issue#28652.

Compiling error, undefined: grpc.SupportPackageIsVersion

Please update to the latest version of gRPC-Go usinggo get google.golang.org/grpc.

How to turn on logging

The default logger is controlled by environment variables. Turn everything onlike this:

$ export GRPC_GO_LOG_VERBOSITY_LEVEL=99$ export GRPC_GO_LOG_SEVERITY_LEVEL=info
The RPC failed with error"code = Unavailable desc = transport is closing"

This error means the connection the RPC is using was closed, and there are manypossible reasons, including:

  1. mis-configured transport credentials, connection failed on handshaking
  2. bytes disrupted, possibly by a proxy in between
  3. server shutdown
  4. Keepalive parameters caused connection shutdown, for example if you haveconfigured your server to terminate connections regularly totrigger DNSlookups.If this is the case, you may want to increase yourMaxConnectionAgeGrace,to allow longer RPC calls to finish.

It can be tricky to debug this because the error happens on the client side butthe root cause of the connection being closed is on the server side. Turn onlogging onboth client and server, and see if there are any transporterrors.

Documentation

Overview

Package grpc implements an RPC system called gRPC.

See grpc.io for more information about gRPC.

Index

Constants

View Source
const (SupportPackageIsVersion3 =trueSupportPackageIsVersion4 =trueSupportPackageIsVersion5 =trueSupportPackageIsVersion6 =trueSupportPackageIsVersion7 =trueSupportPackageIsVersion8 =trueSupportPackageIsVersion9 =true)

The SupportPackageIsVersion variables are referenced from generated protocolbuffer files to ensure compatibility with the gRPC version used. The latestsupport package version is 9.

Older versions are kept for compatibility.

These constants should not be referenced from any other code.

View Source
const Version = "1.71.0"

Version is the current grpc version.

Variables

View Source
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)
View Source
var DefaultBackoffConfig =BackoffConfig{MaxDelay: 120 *time.Second,}

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

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

View Source
var EnableTracingbool

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.

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

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

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

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

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

Functions

funcClientSupportedCompressorsadded inv1.54.0

func ClientSupportedCompressors(ctxcontext.Context) ([]string,error)

ClientSupportedCompressors returns compressor names advertised by the clientvia 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 alater release.

funcCodedeprecated

func Code(errerror)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.

funcErrorDescdeprecated

func ErrorDesc(errerror)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.

funcErrorfdeprecated

func Errorf(ccodes.Code, formatstring, 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.

funcInvoke

func Invoke(ctxcontext.Context, methodstring, args, replyany, cc *ClientConn, opts ...CallOption)error

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

DEPRECATED: Use ClientConn.Invoke instead.

funcMethodadded inv1.11.2

func Method(ctxcontext.Context) (string,bool)

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

funcMethodFromServerStreamadded inv1.8.0

func MethodFromServerStream(streamServerStream) (string,bool)

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

funcNewContextWithServerTransportStreamadded inv1.11.0

func NewContextWithServerTransportStream(ctxcontext.Context, streamServerTransportStream)context.Context

NewContextWithServerTransportStream creates a new context from ctx andattaches stream to it.

Experimental

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

funcSendHeader

func SendHeader(ctxcontext.Context, mdmetadata.MD)error

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

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

funcSetHeaderadded inv1.0.3

func SetHeader(ctxcontext.Context, mdmetadata.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. Allthe 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 whenthe handler returns; for streaming handlers, this can happen when stream'sSendMsg method is called.
  • An RPC status is sent out (error or success). This occurs when the handlerreturns.

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

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

funcSetSendCompressoradded inv1.54.0

func SetSendCompressor(ctxcontext.Context, namestring)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 isused when below conditions are met:

  • compressor is registered via encoding.RegisterCompressor
  • compressor name must exist in the client advertised compressor namessent in grpc-accept-encoding header. Use ClientSupportedCompressors toget 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 theoutbound compression.By default, server messages will be sent using the same compressor withwhich request messages were sent.

It is not safe to call SetSendCompressor concurrently with SendHeader andSendMsg.

Experimental

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

funcSetTrailer

func SetTrailer(ctxcontext.Context, mdmetadata.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, thestatus code will often not match the RPC status as seen by the clientapplication, and therefore, should not be relied upon for this purpose.

Types

typeBackoffConfigdeprecated

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

BackoffConfig defines the parameters for the default gRPC backoff strategy.

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

typeBidiStreamingClientadded inv1.64.0

type BidiStreamingClient[Reqany, Resany] 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 therequest message stream and the type of the response message stream. It isused in generated code.

typeBidiStreamingServeradded inv1.64.0

type BidiStreamingServer[Reqany, Resany] 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 therequest message stream and the type of the response message stream. It isused in generated code.

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

typeCallOption

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

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

funcCallContentSubtypeadded inv1.10.0

func CallContentSubtype(contentSubtypestring)CallOption

CallContentSubtype returns a CallOption that will set the content-subtypefor a call. For example, if content-subtype is "json", the Content-Type overthe wire will be "application/grpc+json". The content-subtype is convertedto lowercase before being included in Content-Type. See Content-Type onhttps://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests formore details.

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

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

funcCallCustomCodecdeprecatedadded inv1.10.0

func CallCustomCodec(codecCodec)CallOption

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

Deprecated: use ForceCodec instead.

funcFailFastdeprecated

func FailFast(failFastbool)CallOption

FailFast is the opposite of WaitForReady.

Deprecated: use WaitForReady.

funcForceCodecadded inv1.19.0

func ForceCodec(codecencoding.Codec)CallOption

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

See Content-Type onhttps://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests formore details. Also see the documentation on RegisterCodec andCallContentSubtype for more details on the interaction between Codec andcontent-subtype.

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

Experimental

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

funcForceCodecV2added inv1.66.0

func ForceCodecV2(codecencoding.CodecV2)CallOption

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

See Content-Type onhttps://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests formore details. Also see the documentation on RegisterCodec andCallContentSubtype for more details on the interaction between Codec andcontent-subtype.

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

Experimental

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

funcHeader

func Header(md *metadata.MD)CallOption

Header returns a CallOptions that retrieves the header metadatafor a unary RPC.

funcMaxCallRecvMsgSizeadded inv1.4.0

func MaxCallRecvMsgSize(bytesint)CallOption

MaxCallRecvMsgSize returns a CallOption which sets the maximum message sizein bytes the client can receive. If this is not set, gRPC uses the default4MB.

funcMaxCallSendMsgSizeadded inv1.4.0

func MaxCallSendMsgSize(bytesint)CallOption

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

funcMaxRetryRPCBufferSizeadded inv1.14.0

func MaxRetryRPCBufferSize(bytesint)CallOption

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

Experimental

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

funcOnFinishadded inv1.54.0

func OnFinish(onFinish func(errerror))CallOption

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

Experimental

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

funcPeeradded inv1.2.0

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.

funcPerRPCCredentialsadded inv1.4.0

func PerRPCCredentials(credscredentials.PerRPCCredentials)CallOption

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

funcStaticMethodadded inv1.62.0

func StaticMethod()CallOption

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

funcTrailer

func Trailer(md *metadata.MD)CallOption

Trailer returns a CallOptions that retrieves the trailer metadatafor a unary RPC.

funcUseCompressoradded inv1.8.0

func UseCompressor(namestring)CallOption

UseCompressor returns a CallOption which sets the compressor used whensending the request. If WithCompressor is also set, UseCompressor hashigher priority.

Experimental

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

funcWaitForReadyadded inv1.18.0

func WaitForReady(waitForReadybool)CallOption

WaitForReady configures the RPC's behavior when the client is inTRANSIENT_FAILURE, which occurs when all addresses fail to connect. IfwaitForReady is false, the RPC will fail immediately. Otherwise, the clientwill wait until a connection becomes available or the RPC's deadline isreached.

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

typeClientConn

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

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

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

A ClientConn encapsulates a range of functionality including nameresolution, TCP connection establishment (with retries and backoff) and TLShandshakes. It also handles errors on established connections byre-resolving the name and reconnecting.

funcDialdeprecated

func Dial(targetstring, opts ...DialOption) (*ClientConn,error)

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

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

funcDialContextdeprecatedadded inv1.0.2

func DialContext(ctxcontext.Context, targetstring, opts ...DialOption) (conn *ClientConn, errerror)

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

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

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

funcNewClientadded inv1.63.0

func NewClient(targetstring, opts ...DialOption) (conn *ClientConn, errerror)

NewClient creates a new gRPC "channel" for the target URI provided. No I/Ois performed. Use of the ClientConn for RPCs will automatically cause it toconnect. 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 inhttps://github.com/grpc/grpc/blob/master/doc/naming.md. E.g. to use the dnsname resolver, a "dns:///" prefix may be applied to the target. The defaultname resolver will be used if no scheme is detected, or if the parsed schemeis not a registered name resolver. The default resolver is "dns" but can beoverridden 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 thisfunction.

func (*ClientConn)CanonicalTargetadded inv1.63.0

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"

func (*ClientConn)Close

func (cc *ClientConn) Close()error

Close tears down the ClientConn and all underlying connections.

func (*ClientConn)Connectadded inv1.41.0

func (cc *ClientConn) Connect()

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

Experimental

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

func (*ClientConn)GetMethodConfigadded inv1.4.0

func (cc *ClientConn) GetMethodConfig(methodstring)MethodConfig

GetMethodConfig gets the method config of the input method.If there's an exact match for input method (i.e. /service/method), we returnthe corresponding MethodConfig.If there isn't an exact match for the input method, we look for the service's defaultconfig 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.

func (*ClientConn)GetStateadded inv1.5.2

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

GetState returns the connectivity.State of ClientConn.

func (*ClientConn)Invokeadded inv1.8.0

func (cc *ClientConn) Invoke(ctxcontext.Context, methodstring, args, replyany, opts ...CallOption)error

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

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

func (*ClientConn)NewStreamadded inv1.8.0

func (cc *ClientConn) NewStream(ctxcontext.Context, desc *StreamDesc, methodstring, opts ...CallOption) (ClientStream,error)

NewStream creates a new Stream for the client side. This is typicallycalled 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 followingactions 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-generatedclient-streaming RPC, for instance, might use the helper functionCloseAndRecv (note that CloseSend does not Recv, therefore is notguaranteed 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 grpcwill not call the optionally-configured stats handler with a stats.End message.

func (*ClientConn)ResetConnectBackoffadded inv1.15.0

func (cc *ClientConn) ResetConnectBackoff()

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

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

Experimental

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

func (*ClientConn)Targetadded inv1.14.0

func (cc *ClientConn) Target()string

Target returns the target string of the ClientConn.

func (*ClientConn)WaitForStateChangeadded inv1.5.2

func (cc *ClientConn) WaitForStateChange(ctxcontext.Context, sourceStateconnectivity.State)bool

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

typeClientConnInterfaceadded inv1.27.0

type ClientConnInterface interface {// Invoke performs a unary RPC and returns after the response is received// into reply.Invoke(ctxcontext.Context, methodstring, argsany, replyany, opts ...CallOption)error// NewStream begins a streaming RPC.NewStream(ctxcontext.Context, desc *StreamDesc, methodstring, opts ...CallOption) (ClientStream,error)}

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

typeClientStream

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. It closes the stream// when non-nil error is met. 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(many)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(many)error}

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

All errors returned from ClientStream methods are compatible with thestatus package.

funcNewClientStream

func NewClientStream(ctxcontext.Context, desc *StreamDesc, cc *ClientConn, methodstring, opts ...CallOption) (ClientStream,error)

NewClientStream is a wrapper for ClientConn.NewStream.

typeClientStreamingClientadded inv1.64.0

type ClientStreamingClient[Reqany, Resany] 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 (manyrequests, one response) RPC. It is generic over both the type of the requestmessage stream and the type of the unary response message. It is used ingenerated code.

typeClientStreamingServeradded inv1.64.0

type ClientStreamingServer[Reqany, Resany] 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 (manyrequests, one response) RPC. It is generic over both the type of the requestmessage stream and the type of the unary response message. It is used ingenerated code.

To terminate the RPC, call SendAndClose and return nil from the methodhandler or do not call SendAndClose and return an error from the statuspackage.

typeCodecdeprecated

type Codec interface {// Marshal returns the wire format of v.Marshal(vany) ([]byte,error)// Unmarshal parses the wire format into v.Unmarshal(data []byte, vany)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.

typeCompressordeprecated

type Compressor interface {// Do compresses p into w.Do(wio.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.

funcNewGZIPCompressordeprecated

func NewGZIPCompressor()Compressor

NewGZIPCompressor creates a Compressor based on GZIP.

Deprecated: use package encoding/gzip.

funcNewGZIPCompressorWithLeveldeprecatedadded inv1.11.0

func NewGZIPCompressorWithLevel(levelint) (Compressor,error)

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

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

Deprecated: use package encoding/gzip.

typeCompressorCallOptionadded inv1.11.0

type CompressorCallOption struct {CompressorTypestring}

CompressorCallOption is a CallOption that indicates the compressor to use.

Experimental

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

typeConnectParamsadded inv1.25.0

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

ConnectParams defines the parameters for connecting and retrying. Users areencouraged to use this instead of the BackoffConfig type defined above. Seehere 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 alater release.

typeContentSubtypeCallOptionadded inv1.11.0

type ContentSubtypeCallOption struct {ContentSubtypestring}

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

Experimental

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

typeCustomCodecCallOptionadded inv1.11.0

type CustomCodecCallOption struct {CodecCodec}

CustomCodecCallOption is a CallOption that indicates the codec used formarshaling messages.

Experimental

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

typeDecompressordeprecated

type Decompressor interface {// Do reads the data from r and uncompress them.Do(rio.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.

funcNewGZIPDecompressordeprecated

func NewGZIPDecompressor()Decompressor

NewGZIPDecompressor creates a Decompressor based on GZIP.

Deprecated: use package encoding/gzip.

typeDialOption

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

DialOption configures how we set up the connection.

funcFailOnNonTempDialErrordeprecatedadded inv1.0.5

func FailOnNonTempDialError(fbool)DialOption

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

FailOnNonTempDialError only affects the initial dial, and does not doanything 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 alater release.

funcWithAuthorityadded inv1.2.0

func WithAuthority(astring)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.

funcWithBackoffConfigdeprecated

func WithBackoffConfig(bBackoffConfig)DialOption

WithBackoffConfig configures the dialer to use the provided backoffparameters after connection failures.

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

funcWithBackoffMaxDelaydeprecated

func WithBackoffMaxDelay(mdtime.Duration)DialOption

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

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

funcWithBlockdeprecated

func WithBlock()DialOption

WithBlock returns a DialOption which makes callers of Dial block until theunderlying connection is up. Without this, Dial returns immediately andconnecting 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.

funcWithChainStreamInterceptoradded inv1.21.0

func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor)DialOption

WithChainStreamInterceptor returns a DialOption that specifies the chainedinterceptor 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 interceptordefined by WithStreamInterceptor will always be prepended to the chain.

funcWithChainUnaryInterceptoradded inv1.21.0

func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor)DialOption

WithChainUnaryInterceptor returns a DialOption that specifies the chainedinterceptor 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 interceptordefined by WithUnaryInterceptor will always be prepended to the chain.

funcWithChannelzParentIDadded inv1.12.0

func WithChannelzParentID(cchannelz.Identifier)DialOption

WithChannelzParentID returns a DialOption that specifies the channelz ID ofcurrent 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 alater release.

funcWithCodecdeprecated

func WithCodec(cCodec)DialOption

WithCodec returns a DialOption which sets a codec for message marshaling andunmarshaling.

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

funcWithCompressordeprecated

func WithCompressor(cpCompressor)DialOption

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

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

funcWithConnectParamsadded inv1.25.0

func WithConnectParams(pConnectParams)DialOption

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

The backoff configuration specified as part of the ConnectParams overridesall defaults specified inhttps://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Considerusing the backoff.DefaultConfig as a base, in cases where you want tooverride only a subset of the backoff configuration.

funcWithContextDialeradded inv1.19.0

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

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

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

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

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

funcWithCredentialsBundleadded inv1.16.0

func WithCredentialsBundle(bcredentials.Bundle)DialOption

WithCredentialsBundle returns a DialOption to set a credentials bundle forthe ClientConn.WithCreds. This should not be used together withWithTransportCredentials.

Experimental

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

funcWithDecompressordeprecated

func WithDecompressor(dcDecompressor)DialOption

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

Deprecated: use encoding.RegisterCompressor instead. Will be supportedthroughout 1.x.

funcWithDefaultCallOptionsadded inv1.4.0

func WithDefaultCallOptions(cos ...CallOption)DialOption

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

funcWithDefaultServiceConfigadded inv1.20.0

func WithDefaultServiceConfig(sstring)DialOption

WithDefaultServiceConfig returns a DialOption that configures the defaultservice 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 aninvalid 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.mdFor a simple example of usage, see:examples/features/load_balancing/client/main.go

funcWithDialerdeprecated

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

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

Deprecated: use WithContextDialer instead. Will be supported throughout1.x.

funcWithDisableHealthCheckadded inv1.17.0

func WithDisableHealthCheck()DialOption

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

Experimental

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

funcWithDisableRetryadded inv1.14.0

func WithDisableRetry()DialOption

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

funcWithDisableServiceConfigadded inv1.12.0

func WithDisableServiceConfig()DialOption

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

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

funcWithIdleTimeoutadded inv1.56.0

func WithIdleTimeout(dtime.Duration)DialOption

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

A default timeout of 30 minutes will be used if this dial option is not setat 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 alater release.

funcWithInitialConnWindowSizeadded inv1.4.0

func WithInitialConnWindowSize(sint32)DialOption

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

funcWithInitialWindowSizeadded inv1.4.0

func WithInitialWindowSize(sint32)DialOption

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

funcWithInsecuredeprecated

func WithInsecure()DialOption

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

Note that using this DialOption with per-RPC credentials (throughWithCredentialsBundle or WithPerRPCCredentials) which require transportsecurity is incompatible and will cause grpc.Dial() to fail.

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

funcWithKeepaliveParamsadded inv1.2.0

func WithKeepaliveParams(kpkeepalive.ClientParameters)DialOption

WithKeepaliveParams returns a DialOption that specifies keepalive parametersfor the client transport.

Keepalive is disabled by default.

funcWithLocalDNSResolutionadded inv1.71.0

func WithLocalDNSResolution()DialOption

WithLocalDNSResolution forces local DNS name resolution even when a proxy isspecified in the environment. By default, the server name is provideddirectly to the proxy as part of the CONNECT handshake. This is ignored ifWithNoProxy is used.

Experimental

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

funcWithMaxCallAttemptsadded inv1.65.0

func WithMaxCallAttempts(nint)DialOption

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

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

funcWithMaxHeaderListSizeadded inv1.14.0

func WithMaxHeaderListSize(suint32)DialOption

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

funcWithMaxMsgSizedeprecatedadded inv1.2.0

func WithMaxMsgSize(sint)DialOption

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

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

funcWithNoProxyadded inv1.29.0

func WithNoProxy()DialOption

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

Experimental

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

funcWithPerRPCCredentials

func WithPerRPCCredentials(credscredentials.PerRPCCredentials)DialOption

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

funcWithReadBufferSizeadded inv1.7.0

func WithReadBufferSize(sint)DialOption

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

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

funcWithResolversadded inv1.27.0

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

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

Experimental

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

funcWithReturnConnectionErrordeprecatedadded inv1.30.0

func WithReturnConnectionError()DialOption

WithReturnConnectionError returns a DialOption which makes the client connectionreturn a string containing both the last connection error that occurred andthe 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.

funcWithSharedWriteBufferadded inv1.58.0

func WithSharedWriteBuffer(valbool)DialOption

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

Experimental

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

funcWithStatsHandleradded inv1.2.0

func WithStatsHandler(hstats.Handler)DialOption

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

funcWithStreamInterceptoradded inv1.0.2

func WithStreamInterceptor(fStreamClientInterceptor)DialOption

WithStreamInterceptor returns a DialOption that specifies the interceptor forstreaming RPCs.

funcWithTimeoutdeprecated

func WithTimeout(dtime.Duration)DialOption

WithTimeout returns a DialOption that configures a timeout for dialing aClientConn 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.

funcWithTransportCredentials

func WithTransportCredentials(credscredentials.TransportCredentials)DialOption

WithTransportCredentials returns a DialOption which configures a connectionlevel security credentials (e.g., TLS/SSL). This should not be used togetherwith WithCredentialsBundle.

funcWithUnaryInterceptoradded inv1.0.2

func WithUnaryInterceptor(fUnaryClientInterceptor)DialOption

WithUnaryInterceptor returns a DialOption that specifies the interceptor forunary RPCs.

funcWithUserAgent

func WithUserAgent(sstring)DialOption

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

funcWithWriteBufferSizeadded inv1.7.0

func WithWriteBufferSize(sint)DialOption

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

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

typeEmptyCallOptionadded inv1.4.0

type EmptyCallOption struct{}

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

typeEmptyDialOptionadded inv1.14.0

type EmptyDialOption struct{}

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

Experimental

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

typeEmptyServerOptionadded inv1.21.0

type EmptyServerOption struct{}

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

Experimental

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

typeFailFastCallOptionadded inv1.11.0

type FailFastCallOption struct {FailFastbool}

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

Experimental

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

typeForceCodecCallOptionadded inv1.19.0

type ForceCodecCallOption struct {Codecencoding.Codec}

ForceCodecCallOption is a CallOption that indicates the codec used formarshaling messages.

Experimental

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

typeForceCodecV2CallOptionadded inv1.66.0

type ForceCodecV2CallOption struct {CodecV2encoding.CodecV2}

ForceCodecV2CallOption is a CallOption that indicates the codec used formarshaling messages.

Experimental

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

typeGenericClientStreamadded inv1.64.0

type GenericClientStream[Reqany, Resany] struct {ClientStream}

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

func (*GenericClientStream[Req, Res])CloseAndRecvadded inv1.64.0

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

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

func (*GenericClientStream[Req, Res])Recvadded inv1.64.0

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 parameterof the GenericClientStream receiver.

func (*GenericClientStream[Req, Res])Sendadded inv1.64.0

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

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

typeGenericServerStreamadded inv1.64.0

type GenericServerStream[Reqany, Resany] struct {ServerStream}

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

func (*GenericServerStream[Req, Res])Recvadded inv1.64.0

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 parameterof the clientStreamServer receiver.

func (*GenericServerStream[Req, Res])Sendadded inv1.64.0

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

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

func (*GenericServerStream[Req, Res])SendAndCloseadded inv1.64.0

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

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

typeHeaderCallOptionadded inv1.11.0

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 alater release.

typeMaxHeaderListSizeDialOptionadded inv1.64.0

type MaxHeaderListSizeDialOption struct {MaxHeaderListSizeuint32}

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

typeMaxHeaderListSizeServerOptionadded inv1.64.0

type MaxHeaderListSizeServerOption struct {MaxHeaderListSizeuint32}

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

typeMaxRecvMsgSizeCallOptionadded inv1.11.0

type MaxRecvMsgSizeCallOption struct {MaxRecvMsgSizeint}

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

Experimental

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

typeMaxRetryRPCBufferSizeCallOptionadded inv1.14.0

type MaxRetryRPCBufferSizeCallOption struct {MaxRetryRPCBufferSizeint}

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

Experimental

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

typeMaxSendMsgSizeCallOptionadded inv1.11.0

type MaxSendMsgSizeCallOption struct {MaxSendMsgSizeint}

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

Experimental

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

typeMethodConfigdeprecatedadded inv1.2.0

MethodConfig defines the configuration recommended by the service providers for aparticular method.

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

typeMethodDesc

type MethodDesc struct {MethodNamestringHandlerMethodHandler}

MethodDesc represents an RPC service's method specification.

typeMethodHandleradded inv1.69.0

type MethodHandler func(srvany, ctxcontext.Context, dec func(any)error, interceptorUnaryServerInterceptor) (any,error)

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

typeMethodInfo

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

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

typeOnFinishCallOptionadded inv1.54.0

type OnFinishCallOption struct {OnFinish func(error)}

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

Experimental

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

typePeerCallOptionadded inv1.11.0

type PeerCallOption struct {PeerAddr *peer.Peer}

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

Experimental

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

typePerRPCCredsCallOptionadded inv1.11.0

type PerRPCCredsCallOption struct {Credscredentials.PerRPCCredentials}

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

Experimental

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

typePreparedMsgadded inv1.21.0

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 alater release.

func (*PreparedMsg)Encodeadded inv1.21.0

func (p *PreparedMsg) Encode(sStream, msgany)error

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

typeServer

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

Server is a gRPC server to serve RPC requests.

funcNewServer

func NewServer(opt ...ServerOption) *Server

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

func (*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>.

func (*Server)GracefulStopadded inv1.0.2

func (s *Server) GracefulStop()

GracefulStop stops the gRPC server gracefully. It stops the server fromaccepting new connections and RPCs and blocks until all the pending RPCs arefinished.

func (*Server)RegisterService

func (s *Server) RegisterService(sd *ServiceDesc, ssany)

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

func (*Server)Serve

func (s *Server) Serve(lisnet.Listener)error

Serve accepts incoming connections on the listener lis, creating a newServerTransport and service goroutine for each. The service goroutinesread 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 whenthis 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 OSdefaults for TCP keepalive time and interval to 15s. To enable TCP keepalivewith OS defaults for keepalive time and interval, callers need to do thefollowing two things:

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

func (*Server)ServeHTTP

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

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

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

To share one port (such as 443 for https) between gRPC and anexisting 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 totallyseparate from grpc-go's HTTP/2 server. Performance and features may varybetween the two paths. ServeHTTP does not support some gRPC featuresavailable through grpc-go's HTTP/2 server.

Experimental

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

func (*Server)Stop

func (s *Server) Stop()

Stop stops the gRPC server. It immediately closes all openconnections and listeners.It cancels all active RPCs on the server side and the correspondingpending RPCs on the client side will get notified by connectionerrors.

typeServerOption

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

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

funcChainStreamInterceptoradded inv1.28.0

func ChainStreamInterceptor(interceptors ...StreamServerInterceptor)ServerOption

ChainStreamInterceptor returns a ServerOption that specifies the chained interceptorfor 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.

funcChainUnaryInterceptoradded inv1.28.0

func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor)ServerOption

ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptorfor 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.

funcConnectionTimeoutadded inv1.7.3

func ConnectionTimeout(dtime.Duration)ServerOption

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

Experimental

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

funcCreds

Creds returns a ServerOption that sets credentials for server connections.

funcCustomCodecdeprecated

func CustomCodec(codecCodec)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 willautomatically use registered codecs based on the incoming requests' headers.See alsohttps://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec.Will be supported throughout 1.x.

funcForceServerCodecadded inv1.38.0

func ForceServerCodec(codecencoding.Codec)ServerOption

ForceServerCodec returns a ServerOption that sets a codec for messagemarshaling and unmarshaling.

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

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

This function is provided for advanced users; prefer to register codecsusing encoding.RegisterCodec.The server will automatically use registered codecs based on the incomingrequests' headers. See alsohttps://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 alater release.

funcForceServerCodecV2added inv1.66.0

func ForceServerCodecV2(codecV2encoding.CodecV2)ServerOption

ForceServerCodecV2 is the equivalent of ForceServerCodec, but for the newCodecV2 interface.

Will be supported throughout 1.x.

Experimental

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

funcHeaderTableSizeadded inv1.25.0

func HeaderTableSize(suint32)ServerOption

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

Experimental

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

funcInTapHandleadded inv1.0.5

func InTapHandle(htap.ServerInHandle)ServerOption

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

Experimental

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

funcInitialConnWindowSizeadded inv1.4.0

func InitialConnWindowSize(sint32)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.

funcInitialWindowSizeadded inv1.4.0

func InitialWindowSize(sint32)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.

funcKeepaliveEnforcementPolicyadded inv1.3.0

func KeepaliveEnforcementPolicy(kepkeepalive.EnforcementPolicy)ServerOption

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

funcKeepaliveParamsadded inv1.3.0

func KeepaliveParams(kpkeepalive.ServerParameters)ServerOption

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

funcMaxConcurrentStreams

func MaxConcurrentStreams(nuint32)ServerOption

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

funcMaxHeaderListSizeadded inv1.14.0

func MaxHeaderListSize(suint32)ServerOption

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

funcMaxMsgSizedeprecatedadded inv1.0.2

func MaxMsgSize(mint)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.

funcMaxRecvMsgSizeadded inv1.4.0

func MaxRecvMsgSize(mint)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.

funcMaxSendMsgSizeadded inv1.4.0

func MaxSendMsgSize(mint)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`.

funcNumStreamWorkersadded inv1.30.0

func NumStreamWorkers(numServerWorkersuint32)ServerOption

NumStreamWorkers returns a ServerOption that sets the number of workergoroutines that should be used to process incoming streams. Setting this tozero (default) will disable workers and spawn a new goroutine for eachstream.

Experimental

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

funcRPCCompressordeprecated

func RPCCompressor(cpCompressor)ServerOption

RPCCompressor returns a ServerOption that sets a compressor for outboundmessages. For backward compatibility, all outbound messages will be sentusing this compressor, regardless of incoming message compression. Bydefault, server messages will be sent using the same compressor with whichrequest messages were sent.

Deprecated: use encoding.RegisterCompressor instead. Will be supportedthroughout 1.x.

funcRPCDecompressordeprecated

func RPCDecompressor(dcDecompressor)ServerOption

RPCDecompressor returns a ServerOption that sets a decompressor for inboundmessages. It has higher priority than decompressors registered viaencoding.RegisterCompressor.

Deprecated: use encoding.RegisterCompressor instead. Will be supportedthroughout 1.x.

funcReadBufferSizeadded inv1.7.0

func ReadBufferSize(sint)ServerOption

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

funcSharedWriteBufferadded inv1.58.0

func SharedWriteBuffer(valbool)ServerOption

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

Experimental

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

funcStatsHandleradded inv1.2.0

func StatsHandler(hstats.Handler)ServerOption

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

funcStreamInterceptor

func StreamInterceptor(iStreamServerInterceptor)ServerOption

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

funcUnaryInterceptor

func UnaryInterceptor(iUnaryServerInterceptor)ServerOption

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

funcUnknownServiceHandleradded inv1.2.0

func UnknownServiceHandler(streamHandlerStreamHandler)ServerOption

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

funcWaitForHandlersadded inv1.61.0

func WaitForHandlers(wbool)ServerOption

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

Experimental

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

funcWriteBufferSizeadded inv1.7.0

func WriteBufferSize(sint)ServerOption

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

typeServerStream

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(many)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(many)error}

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

Errors returned from ServerStream methods are compatible with the statuspackage. However, the status code will often not match the RPC status asseen by the client application, and therefore, should not be relied upon forthis purpose.

typeServerStreamingClientadded inv1.64.0

type ServerStreamingClient[Resany] 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 (onerequest, many responses) RPC. It is generic over the type of the responsemessage. It is used in generated code.

typeServerStreamingServeradded inv1.64.0

type ServerStreamingServer[Resany] 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 (onerequest, many responses) RPC. It is generic over the type of the responsemessage. It is used in generated code.

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

typeServerTransportStreamadded inv1.11.0

type ServerTransportStream interface {Method()stringSetHeader(mdmetadata.MD)errorSendHeader(mdmetadata.MD)errorSetTrailer(mdmetadata.MD)error}

ServerTransportStream is a minimal interface that a transport stream mustimplement. This can be used to mock an actual transport stream for tests ofhandler code that use, for example, grpc.SetHeader (which requires somestream to be in context).

See also NewContextWithServerTransportStream.

Experimental

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

funcServerTransportStreamFromContextadded inv1.12.0

func ServerTransportStreamFromContext(ctxcontext.Context)ServerTransportStream

ServerTransportStreamFromContext returns the ServerTransportStream saved inctx. 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 alater release.

typeServiceConfigdeprecatedadded inv1.2.0

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 howclients that connect to the service should behave.

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

typeServiceDesc

type ServiceDesc struct {ServiceNamestring// The pointer to the service interface. Used to check whether the user// provided implementation satisfies the interface requirements.HandlerTypeanyMethods     []MethodDescStreams     []StreamDescMetadataany}

ServiceDesc represents an RPC service's specification.

typeServiceInfo

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

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

typeServiceRegistraradded inv1.32.0

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, implany)}

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

typeStaticMethodCallOptionadded inv1.62.0

type StaticMethodCallOption struct {EmptyCallOption}

StaticMethodCallOption is a CallOption that specifies that a call comesfrom a static method.

typeStreamdeprecated

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

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

Deprecated: See ClientStream and ServerStream documentation instead.

typeStreamClientInterceptoradded inv1.0.2

type StreamClientInterceptor func(ctxcontext.Context, desc *StreamDesc, cc *ClientConn, methodstring, streamerStreamer, opts ...CallOption) (ClientStream,error)

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

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

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

typeStreamDesc

type StreamDesc struct {// StreamName and Handler are only used when registering handlers on a// server.StreamNamestring// the name of the method excluding the serviceHandlerStreamHandler// 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.ServerStreamsbool// indicates the server can perform streaming sendsClientStreamsbool// indicates the client can perform streaming sends}

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

typeStreamHandler

type StreamHandler func(srvany, streamServerStream)error

StreamHandler defines the handler called by gRPC server to complete theexecution of a streaming RPC.

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

typeStreamServerInfo

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

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

typeStreamServerInterceptor

type StreamServerInterceptor func(srvany, ssServerStream, info *StreamServerInfo, handlerStreamHandler)error

StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server.info contains all the information of this RPC the interceptor can operate on. And handler is theservice method implementation. It is the responsibility of the interceptor to invoke handler tocomplete the RPC.

typeStreameradded inv1.0.2

type Streamer func(ctxcontext.Context, desc *StreamDesc, cc *ClientConn, methodstring, opts ...CallOption) (ClientStream,error)

Streamer is called by StreamClientInterceptor to create a ClientStream.

typeTrailerCallOptionadded inv1.11.0

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 alater release.

typeUnaryClientInterceptoradded inv1.0.2

type UnaryClientInterceptor func(ctxcontext.Context, methodstring, req, replyany, cc *ClientConn, invokerUnaryInvoker, opts ...CallOption)error

UnaryClientInterceptor intercepts the execution of a unary RPC on the client.Unary interceptors can be specified as a DialOption, usingWithUnaryInterceptor() or WithChainUnaryInterceptor(), when creating aClientConn. When a unary interceptor(s) is set on a ClientConn, gRPCdelegates all unary RPC invocations to the interceptor, and it is theresponsibility of the interceptor to call invoker to complete the processingof the RPC.

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

The returned error must be compatible with the status package.

typeUnaryHandler

type UnaryHandler func(ctxcontext.Context, reqany) (any,error)

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

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

typeUnaryInvokeradded inv1.0.2

type UnaryInvoker func(ctxcontext.Context, methodstring, req, replyany, cc *ClientConn, opts ...CallOption)error

UnaryInvoker is called by UnaryClientInterceptor to complete RPCs.

typeUnaryServerInfo

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

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

typeUnaryServerInterceptor

type UnaryServerInterceptor func(ctxcontext.Context, reqany, info *UnaryServerInfo, handlerUnaryHandler) (respany, errerror)

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

Source Files

View all Source files

Directories

PathSynopsis
Package admin provides a convenient method for registering a collection of administration services to a gRPC server.
Package admin provides a convenient method for registering a collection of administration services to a gRPC server.
test
Package test contains test only functions for package admin.
Package test contains test only functions for package admin.
Package attributes defines a generic key/value store used in various gRPC components.
Package attributes defines a generic key/value store used in various gRPC components.
Package authz exposes methods to manage authorization within gRPC.
Package authz exposes methods to manage authorization within gRPC.
audit
Package audit contains interfaces for audit logging during authorization.
Package audit contains interfaces for audit logging during authorization.
audit/stdout
Package stdout defines an stdout audit logger.
Package stdout defines an stdout audit logger.
Package backoff provides configuration options for backoff.
Package backoff provides configuration options for backoff.
Package balancer defines APIs for load balancing in gRPC.
Package balancer defines APIs for load balancing in gRPC.
base
Package base defines a balancer base that can be used to build balancers with different picking algorithms.
Package base defines a balancer base that can be used to build balancers with different picking algorithms.
endpointsharding
Package endpointsharding implements a load balancing policy that manages homogeneous child policies each owning a single endpoint.
Package endpointsharding implements a load balancing policy that manages homogeneous child policies each owning a single endpoint.
grpclb
Package grpclb defines a grpclb balancer.
Package grpclb defines a grpclb balancer.
grpclb/state
Package state declares grpclb types to be set by resolvers wishing to pass information to grpclb via resolver.State Attributes.
Package state declares grpclb types to be set by resolvers wishing to pass information to grpclb via resolver.State Attributes.
lazy
Package lazy contains a load balancer that starts in IDLE instead of CONNECTING.
Package lazy contains a load balancer that starts in IDLE instead of CONNECTING.
leastrequest
Package leastrequest implements a least request load balancer.
Package leastrequest implements a least request load balancer.
pickfirst
Package pickfirst contains the pick_first load balancing policy.
Package pickfirst contains the pick_first load balancing policy.
pickfirst/internal
Package internal contains code internal to the pickfirst package.
Package internal contains code internal to the pickfirst package.
pickfirst/pickfirstleaf
Package pickfirstleaf contains the pick_first load balancing policy which will be the universal leaf policy after dualstack changes are implemented.
Package pickfirstleaf contains the pick_first load balancing policy which will be the universal leaf policy after dualstack changes are implemented.
rls
Package rls implements the RLS LB policy.
Package rls implements the RLS LB policy.
rls/internal/adaptive
Package adaptive provides functionality for adaptive client-side throttling.
Package adaptive provides functionality for adaptive client-side throttling.
rls/internal/keys
Package keys provides functionality required to build RLS request keys.
Package keys provides functionality required to build RLS request keys.
rls/internal/test/e2e
Package e2e contains utilities for end-to-end RouteLookupService tests.
Package e2e contains utilities for end-to-end RouteLookupService tests.
roundrobin
Package roundrobin defines a roundrobin balancer.
Package roundrobin defines a roundrobin balancer.
weightedroundrobin
Package weightedroundrobin provides an implementation of the weighted round robin LB policy, as defined in [gRFC A58].
Package weightedroundrobin provides an implementation of the weighted round robin LB policy, as defined in [gRFC A58].
weightedroundrobin/internal
Package internal allows for easier testing of the weightedroundrobin package.
Package internal allows for easier testing of the weightedroundrobin package.
weightedtarget
Package weightedtarget implements the weighted_target balancer.
Package weightedtarget implements the weighted_target balancer.
weightedtarget/weightedaggregator
Package weightedaggregator implements state aggregator for weighted_target balancer.
Package weightedaggregator implements state aggregator for weighted_target balancer.
Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks.
Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks.
benchmain
Package main provides benchmark with setting flags.
Package main provides benchmark with setting flags.
benchresult
To format the benchmark result:
To format the benchmark result:
client
Package main provides a client used for benchmarking.
Package main provides a client used for benchmarking.
flags
Package flags provide convenience types and routines to accept specific types of flag values on the command line.
Package flags provide convenience types and routines to accept specific types of flag values on the command line.
latency
Package latency provides wrappers for net.Conn, net.Listener, and net.Dialers, designed to interoperate to inject real-world latency into network connections.
Package latency provides wrappers for net.Conn, net.Listener, and net.Dialers, designed to interoperate to inject real-world latency into network connections.
server
Package main provides a server used for benchmarking.
Package main provides a server used for benchmarking.
stats
Package stats tracks the statistics associated with benchmark runs.
Package stats tracks the statistics associated with benchmark runs.
worker
Binary worker implements the benchmark worker that can turn into a benchmark client or server.
Binary worker implements the benchmark worker that can turn into a benchmark client or server.
Package binarylog implementation binary logging as defined in https://github.com/grpc/proposal/blob/master/A16-binary-logging.md.
Package binarylog implementation binary logging as defined in https://github.com/grpc/proposal/blob/master/A16-binary-logging.md.
Package channelz exports internals of the channelz implementation as required by other gRPC packages.
Package channelz exports internals of the channelz implementation as required by other gRPC packages.
internal/protoconv
Package protoconv supports converting between the internal channelz implementation and the protobuf representation of all the entities.
Package protoconv supports converting between the internal channelz implementation and the protobuf representation of all the entities.
service
Package service provides an implementation for channelz service server.
Package service provides an implementation for channelz service server.
cmd
Package codes defines the canonical error codes used by gRPC.
Package codes defines the canonical error codes used by gRPC.
Package connectivity defines connectivity semantics.
Package connectivity defines connectivity semantics.
Package credentials implements various credentials supported by gRPC library, which encapsulate all the state needed by a client to authenticate with a server and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call.
Package credentials implements various credentials supported by gRPC library, which encapsulate all the state needed by a client to authenticate with a server and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call.
alts
Package alts implements the ALTS credential support by gRPC library, which encapsulates all the state needed by a client to authenticate with a server using ALTS and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call.
Package alts implements the ALTS credential support by gRPC library, which encapsulates all the state needed by a client to authenticate with a server using ALTS and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call.
alts/internal
Package internal contains common core functionality for ALTS.
Package internal contains common core functionality for ALTS.
alts/internal/authinfo
Package authinfo provide authentication information returned by handshakers.
Package authinfo provide authentication information returned by handshakers.
alts/internal/conn
Package conn contains an implementation of a secure channel created by gRPC handshakers.
Package conn contains an implementation of a secure channel created by gRPC handshakers.
alts/internal/handshaker
Package handshaker provides ALTS handshaking functionality for GCP.
Package handshaker provides ALTS handshaking functionality for GCP.
alts/internal/handshaker/service
Package service manages connections between the VM application and the ALTS handshaker service.
Package service manages connections between the VM application and the ALTS handshaker service.
alts/internal/testutil
Package testutil include useful test utilities for the handshaker.
Package testutil include useful test utilities for the handshaker.
google
Package google defines credentials for google cloud services.
Package google defines credentials for google cloud services.
insecure
Package insecure provides an implementation of the credentials.TransportCredentials interface which disables transport security.
Package insecure provides an implementation of the credentials.TransportCredentials interface which disables transport security.
local
Package local implements local transport credentials.
Package local implements local transport credentials.
oauth
Package oauth implements gRPC credentials using OAuth.
Package oauth implements gRPC credentials using OAuth.
sts
Package sts implements call credentials using STS (Security Token Service) as defined in https://tools.ietf.org/html/rfc8693.
Package sts implements call credentials using STS (Security Token Service) as defined in https://tools.ietf.org/html/rfc8693.
tls/certprovider
Package certprovider defines APIs for Certificate Providers in gRPC.
Package certprovider defines APIs for Certificate Providers in gRPC.
tls/certprovider/pemfile
Package pemfile provides a file watching certificate provider plugin implementation which works for files with PEM contents.
Package pemfile provides a file watching certificate provider plugin implementation which works for files with PEM contents.
xds
Package xds provides a transport credentials implementation where the security configuration is pushed by a management server using xDS APIs.
Package xds provides a transport credentials implementation where the security configuration is pushed by a management server using xDS APIs.
Package encoding defines the interface for the compressor and codec, and functions to register and retrieve compressors and codecs.
Package encoding defines the interface for the compressor and codec, and functions to register and retrieve compressors and codecs.
gzip
Package gzip implements and registers the gzip compressor during the initialization.
Package gzip implements and registers the gzip compressor during the initialization.
proto
Package proto defines the protobuf codec.
Package proto defines the protobuf codec.
examplesmodule
Package experimental is a collection of experimental features that might have some rough edges to them.
Package experimental is a collection of experimental features that might have some rough edges to them.
credentials
Package credentials provides experimental TLS credentials.
Package credentials provides experimental TLS credentials.
credentials/internal
Package internal defines APIs for parsing SPIFFE ID.
Package internal defines APIs for parsing SPIFFE ID.
opentelemetry
Package opentelemetry is EXPERIMENTAL and will be moved to stats/opentelemetry package in a later release.
Package opentelemetry is EXPERIMENTAL and will be moved to stats/opentelemetry package in a later release.
stats
Package stats contains experimental metrics/stats API's.
Package stats contains experimental metrics/stats API's.
gcp
Package grpclog defines logging for grpc.
Package grpclog defines logging for grpc.
glogger
Package glogger defines glog-based logging for grpc.
Package glogger defines glog-based logging for grpc.
internal
Package internal contains functionality internal to the grpclog package.
Package internal contains functionality internal to the grpclog package.
Package health provides a service that exposes server's health and it must be imported to enable support for client-side health checks.
Package health provides a service that exposes server's health and it must be imported to enable support for client-side health checks.
Package internal contains gRPC-internal code, to avoid polluting the godoc of the top-level grpc package.
Package internal contains gRPC-internal code, to avoid polluting the godoc of the top-level grpc package.
admin
Package admin contains internal implementation for admin service.
Package admin contains internal implementation for admin service.
backoff
Package backoff implement the backoff strategy for gRPC.
Package backoff implement the backoff strategy for gRPC.
balancer/gracefulswitch
Package gracefulswitch implements a graceful switch load balancer.
Package gracefulswitch implements a graceful switch load balancer.
balancer/nop
Package nop implements a balancer with all of its balancer operations as no-ops, other than returning a Transient Failure Picker on a Client Conn update.
Package nop implements a balancer with all of its balancer operations as no-ops, other than returning a Transient Failure Picker on a Client Conn update.
balancer/stub
Package stub implements a balancer for testing purposes.
Package stub implements a balancer for testing purposes.
balancergroup
Package balancergroup implements a utility struct to bind multiple balancers into one balancer.
Package balancergroup implements a utility struct to bind multiple balancers into one balancer.
balancerload
Package balancerload defines APIs to parse server loads in trailers.
Package balancerload defines APIs to parse server loads in trailers.
binarylog
Package binarylog implementation binary logging as defined in https://github.com/grpc/proposal/blob/master/A16-binary-logging.md.
Package binarylog implementation binary logging as defined in https://github.com/grpc/proposal/blob/master/A16-binary-logging.md.
buffer
Package buffer provides an implementation of an unbounded buffer.
Package buffer provides an implementation of an unbounded buffer.
cache
Package cache implements caches to be used in gRPC.
Package cache implements caches to be used in gRPC.
channelz
Package channelz defines internal APIs for enabling channelz service, entry registration/deletion, and accessing channelz data.
Package channelz defines internal APIs for enabling channelz service, entry registration/deletion, and accessing channelz data.
credentials
Package credentials defines APIs for parsing SPIFFE ID.
Package credentials defines APIs for parsing SPIFFE ID.
credentials/xds
Package xds contains non-user facing functionality of the xds credentials.
Package xds contains non-user facing functionality of the xds credentials.
envconfig
Package envconfig contains grpc settings configured by environment variables.
Package envconfig contains grpc settings configured by environment variables.
googlecloud
Package googlecloud contains internal helpful functions for google cloud.
Package googlecloud contains internal helpful functions for google cloud.
grpclog
Package grpclog provides logging functionality for internal gRPC packages, outside of the functionality provided by the external `grpclog` package.
Package grpclog provides logging functionality for internal gRPC packages, outside of the functionality provided by the external `grpclog` package.
grpcsync
Package grpcsync implements additional synchronization primitives built upon the sync package.
Package grpcsync implements additional synchronization primitives built upon the sync package.
grpctest
Package grpctest implements testing helpers.
Package grpctest implements testing helpers.
grpcutil
Package grpcutil provides utility functions used across the gRPC codebase.
Package grpcutil provides utility functions used across the gRPC codebase.
hierarchy
Package hierarchy contains functions to set and get hierarchy string from addresses.
Package hierarchy contains functions to set and get hierarchy string from addresses.
idle
Package idle contains a component for managing idleness (entering and exiting) based on RPC activity.
Package idle contains a component for managing idleness (entering and exiting) based on RPC activity.
leakcheck
Package leakcheck contains functions to check leaked goroutines and buffers.
Package leakcheck contains functions to check leaked goroutines and buffers.
metadata
Package metadata contains functions to set and get metadata from addresses.
Package metadata contains functions to set and get metadata from addresses.
pretty
Package pretty defines helper functions to pretty-print structs for logging.
Package pretty defines helper functions to pretty-print structs for logging.
profiling
Package profiling contains two logical components: buffer.go and profiling.go.
Package profiling contains two logical components: buffer.go and profiling.go.
profiling/buffer
Package buffer provides a high-performant lock free implementation of a circular buffer used by the profiling code.
Package buffer provides a high-performant lock free implementation of a circular buffer used by the profiling code.
proxyattributes
Package proxyattributes contains functions for getting and setting proxy attributes like the CONNECT address and user info.
Package proxyattributes contains functions for getting and setting proxy attributes like the CONNECT address and user info.
resolver
Package resolver provides internal resolver-related functionality.
Package resolver provides internal resolver-related functionality.
resolver/delegatingresolver
Package delegatingresolver implements a resolver capable of resolving both target URIs and proxy addresses.
Package delegatingresolver implements a resolver capable of resolving both target URIs and proxy addresses.
resolver/dns
Package dns implements a dns resolver to be installed as the default resolver in grpc.
Package dns implements a dns resolver to be installed as the default resolver in grpc.
resolver/dns/internal
Package internal contains functionality internal to the dns resolver package.
Package internal contains functionality internal to the dns resolver package.
resolver/passthrough
Package passthrough implements a pass-through resolver.
Package passthrough implements a pass-through resolver.
resolver/unix
Package unix implements a resolver for unix targets.
Package unix implements a resolver for unix targets.
serviceconfig
Package serviceconfig contains utility functions to parse service config.
Package serviceconfig contains utility functions to parse service config.
stats
Package stats provides internal stats related functionality.
Package stats provides internal stats related functionality.
status
Package status implements errors returned by gRPC.
Package status implements errors returned by gRPC.
stubserver
Package stubserver is a stubbable implementation of google.golang.org/grpc/interop/grpc_testing for testing purposes.
Package stubserver is a stubbable implementation of google.golang.org/grpc/interop/grpc_testing for testing purposes.
syscall
Package syscall provides functionalities that grpc uses to get low-level operating system stats/info.
Package syscall provides functionalities that grpc uses to get low-level operating system stats/info.
testutils
Package testutils contains testing helpers.
Package testutils contains testing helpers.
testutils/fakegrpclb
Package fakegrpclb provides a fake implementation of the grpclb server.
Package fakegrpclb provides a fake implementation of the grpclb server.
testutils/pickfirst
Package pickfirst contains helper functions to check for pickfirst load balancing of RPCs in tests.
Package pickfirst contains helper functions to check for pickfirst load balancing of RPCs in tests.
testutils/proxyserver
Package proxyserver provides an implementation of a proxy server for testing purposes.
Package proxyserver provides an implementation of a proxy server for testing purposes.
testutils/rls
Package rls contains utilities for RouteLookupService e2e tests.
Package rls contains utilities for RouteLookupService e2e tests.
testutils/roundrobin
Package roundrobin contains helper functions to check for roundrobin and weighted-roundrobin load balancing of RPCs in tests.
Package roundrobin contains helper functions to check for roundrobin and weighted-roundrobin load balancing of RPCs in tests.
testutils/stats
Package stats implements a TestMetricsRecorder utility.
Package stats implements a TestMetricsRecorder utility.
testutils/xds/e2e
Package e2e provides utilities for end2end testing of xDS functionality.
Package e2e provides utilities for end2end testing of xDS functionality.
testutils/xds/e2e/setup
Package setup implements setup helpers for xDS e2e tests.
Package setup implements setup helpers for xDS e2e tests.
testutils/xds/fakeserver
Package fakeserver provides a fake implementation of the management server.
Package fakeserver provides a fake implementation of the management server.
transport
Package transport defines and implements message oriented communication channel to complete various transactions (e.g., an RPC).
Package transport defines and implements message oriented communication channel to complete various transactions (e.g., an RPC).
transport/grpchttp2
Package grpchttp2 defines HTTP/2 types and a framer API and implementation.
Package grpchttp2 defines HTTP/2 types and a framer API and implementation.
transport/networktype
Package networktype declares the network type to be used in the default dialer.
Package networktype declares the network type to be used in the default dialer.
wrr
Package wrr contains the interface and common implementations of wrr algorithms.
Package wrr contains the interface and common implementations of wrr algorithms.
xds
Package xds contains methods to Get/Set handshake cluster names.
Package xds contains methods to Get/Set handshake cluster names.
xds/bootstrap
Package bootstrap provides the functionality to initialize certain aspects of an xDS client by reading a bootstrap file.
Package bootstrap provides the functionality to initialize certain aspects of an xDS client by reading a bootstrap file.
xds/bootstrap/tlscreds
Package tlscreds implements mTLS Credentials in xDS Bootstrap File.
Package tlscreds implements mTLS Credentials in xDS Bootstrap File.
xds/matcher
Package matcher contains types that need to be shared between code under google.golang.org/grpc/xds/...
Package matcher contains types that need to be shared between code under google.golang.org/grpc/xds/...
xds/rbac
Package rbac provides service-level and method-level access control for a service.
Package rbac provides service-level and method-level access control for a service.
Package interop contains functions used by interop client/server.
Package interop contains functions used by interop client/server.
alts/client
This binary can only run on Google Cloud Platform (GCP).
This binary can only run on Google Cloud Platform (GCP).
alts/server
This binary can only run on Google Cloud Platform (GCP).
This binary can only run on Google Cloud Platform (GCP).
client
Binary client is an interop client.
Binary client is an interop client.
fake_grpclb
This file is for testing only.
This file is for testing only.
grpclb_fallback
Binary grpclb_fallback is an interop test client for grpclb fallback.
Binary grpclb_fallback is an interop test client for grpclb fallback.
http2
Binary http2 is used to test http2 error edge cases like GOAWAYs and RST_STREAMs
Binary http2 is used to test http2 error edge cases like GOAWAYs and RST_STREAMs
server
Binary server is an interop server.
Binary server is an interop server.
stress/client
client starts an interop client to do stress test and a metrics server to report qps.
client starts an interop client to do stress test and a metrics server to report qps.
stress/metrics_client
Binary metrics_client is a client to retrieve metrics from the server.
Binary metrics_client is a client to retrieve metrics from the server.
xds_federation
Binary client is an interop client.
Binary client is an interop client.
xdsModule
Package keepalive defines configurable parameters for point-to-point healthcheck.
Package keepalive defines configurable parameters for point-to-point healthcheck.
Package mem provides utilities that facilitate memory reuse in byte slices that are used as buffers.
Package mem provides utilities that facilitate memory reuse in byte slices that are used as buffers.
Package metadata define the structure of the metadata supported by gRPC library.
Package metadata define the structure of the metadata supported by gRPC library.
Package orca implements Open Request Cost Aggregation, which is an open standard for request cost aggregation and reporting by backends and the corresponding aggregation of such reports by L7 load balancers (such as Envoy) on the data plane.
Package orca implements Open Request Cost Aggregation, which is an open standard for request cost aggregation and reporting by backends and the corresponding aggregation of such reports by L7 load balancers (such as Envoy) on the data plane.
internal
Package internal contains orca-internal code, for testing purposes and to avoid polluting the godoc of the top-level orca package.
Package internal contains orca-internal code, for testing purposes and to avoid polluting the godoc of the top-level orca package.
Package peer defines various peer information associated with RPCs and corresponding utils.
Package peer defines various peer information associated with RPCs and corresponding utils.
Package profiling exposes methods to manage profiling within gRPC.
Package profiling exposes methods to manage profiling within gRPC.
cmd
Binary cmd is a command-line tool for profiling management.
Binary cmd is a command-line tool for profiling management.
service
Package service defines methods to register a gRPC client/service for a profiling service that is exposed in the same server.
Package service defines methods to register a gRPC client/service for a profiling service that is exposed in the same server.
Package reflection implements server reflection service.
Package reflection implements server reflection service.
internal
Package internal contains code that is shared by both reflection package and the test package.
Package internal contains code that is shared by both reflection package and the test package.
testModule
Package resolver defines APIs for name resolution in gRPC.
Package resolver defines APIs for name resolution in gRPC.
dns
Package dns implements a dns resolver to be installed as the default resolver in grpc.
Package dns implements a dns resolver to be installed as the default resolver in grpc.
manual
Package manual defines a resolver that can be used to manually send resolved addresses to ClientConn.
Package manual defines a resolver that can be used to manually send resolved addresses to ClientConn.
passthrough
Package passthrough implements a pass-through resolver.
Package passthrough implements a pass-through resolver.
security
Package serviceconfig defines types and methods for operating on gRPC service configs.
Package serviceconfig defines types and methods for operating on gRPC service configs.
Package stats is for collecting and reporting various network and RPC stats.
Package stats is for collecting and reporting various network and RPC stats.
opentelemetry
Package opentelemetry implements opentelemetry instrumentation code for gRPC-Go clients and servers.
Package opentelemetry implements opentelemetry instrumentation code for gRPC-Go clients and servers.
opentelemetry/csm
Package csm contains utilities for Google Cloud Service Mesh observability.
Package csm contains utilities for Google Cloud Service Mesh observability.
opentelemetry/internal
Package internal defines the PluginOption interface.
Package internal defines the PluginOption interface.
opentelemetry/internal/testutils
Package testutils contains helpers for OpenTelemetry tests.
Package testutils contains helpers for OpenTelemetry tests.
opentelemetry/internal/tracing
Package tracing implements the OpenTelemetry carrier for context propagation in gRPC tracing.
Package tracing implements the OpenTelemetry carrier for context propagation in gRPC tracing.
Package status implements errors returned by gRPC.
Package status implements errors returned by gRPC.
Package tap defines the function handles which are executed on the transport layer of gRPC-Go and related information.
Package tap defines the function handles which are executed on the transport layer of gRPC-Go and related information.
Package test contains tests.
Package test contains tests.
bufconn
Package bufconn provides a net.Conn implemented by a buffer and related dialing and listening functionality.
Package bufconn provides a net.Conn implemented by a buffer and related dialing and listening functionality.
toolsModule
Package xds contains an implementation of the xDS suite of protocols, to be used by gRPC client and server applications.
Package xds contains an implementation of the xDS suite of protocols, to be used by gRPC client and server applications.
bootstrap
Package bootstrap provides the functionality to register possible options for aspects of the xDS client through the bootstrap file.
Package bootstrap provides the functionality to register possible options for aspects of the xDS client through the bootstrap file.
csds
Package csds implements features to dump the status (xDS responses) the xds_client is using.
Package csds implements features to dump the status (xDS responses) the xds_client is using.
googledirectpath
Package googledirectpath implements a resolver that configures xds to make cloud to prod directpath connection.
Package googledirectpath implements a resolver that configures xds to make cloud to prod directpath connection.
internal
Package internal contains functions/structs shared by xds balancers/resolvers.
Package internal contains functions/structs shared by xds balancers/resolvers.
internal/balancer
Package balancer installs all the xds balancers.
Package balancer installs all the xds balancers.
internal/balancer/cdsbalancer
Package cdsbalancer implements a balancer to handle CDS responses.
Package cdsbalancer implements a balancer to handle CDS responses.
internal/balancer/clusterimpl
Package clusterimpl implements the xds_cluster_impl balancing policy.
Package clusterimpl implements the xds_cluster_impl balancing policy.
internal/balancer/clustermanager
Package clustermanager implements the cluster manager LB policy for xds.
Package clustermanager implements the cluster manager LB policy for xds.
internal/balancer/clusterresolver
Package clusterresolver contains the implementation of the cluster_resolver_experimental LB policy which resolves endpoint addresses using a list of one or more discovery mechanisms.
Package clusterresolver contains the implementation of the cluster_resolver_experimental LB policy which resolves endpoint addresses using a list of one or more discovery mechanisms.
internal/balancer/loadstore
Package loadstore contains the loadStoreWrapper shared by the balancers.
Package loadstore contains the loadStoreWrapper shared by the balancers.
internal/balancer/outlierdetection
Package outlierdetection provides an implementation of the outlier detection LB policy, as defined in https://github.com/grpc/proposal/blob/master/A50-xds-outlier-detection.md.
Package outlierdetection provides an implementation of the outlier detection LB policy, as defined in https://github.com/grpc/proposal/blob/master/A50-xds-outlier-detection.md.
internal/balancer/priority
Package priority implements the priority balancer.
Package priority implements the priority balancer.
internal/balancer/ringhash
Package ringhash implements the ringhash balancer.
Package ringhash implements the ringhash balancer.
internal/balancer/wrrlocality
Package wrrlocality provides an implementation of the wrr locality LB policy, as defined in [A52 - xDS Custom LB Policies].
Package wrrlocality provides an implementation of the wrr locality LB policy, as defined in [A52 - xDS Custom LB Policies].
internal/clients
Package clients provides implementations of the xDS and LRS clients, enabling applications to communicate with xDS management servers and report load.
Package clients provides implementations of the xDS and LRS clients, enabling applications to communicate with xDS management servers and report load.
internal/clusterspecifier
Package clusterspecifier contains the ClusterSpecifier interface and a registry for storing and retrieving their implementations.
Package clusterspecifier contains the ClusterSpecifier interface and a registry for storing and retrieving their implementations.
internal/clusterspecifier/rls
Package rls implements the RLS cluster specifier plugin.
Package rls implements the RLS cluster specifier plugin.
internal/httpfilter
Package httpfilter contains the HTTPFilter interface and a registry for storing and retrieving their implementations.
Package httpfilter contains the HTTPFilter interface and a registry for storing and retrieving their implementations.
internal/httpfilter/fault
Package fault implements the Envoy Fault Injection HTTP filter.
Package fault implements the Envoy Fault Injection HTTP filter.
internal/httpfilter/rbac
Package rbac implements the Envoy RBAC HTTP filter.
Package rbac implements the Envoy RBAC HTTP filter.
internal/httpfilter/router
Package router implements the Envoy Router HTTP filter.
Package router implements the Envoy Router HTTP filter.
internal/resolver
Package resolver implements the xds resolver, that does LDS and RDS to find the cluster to use.
Package resolver implements the xds resolver, that does LDS and RDS to find the cluster to use.
internal/resolver/internal
Package internal contains functionality internal to the xDS resolver.
Package internal contains functionality internal to the xDS resolver.
internal/server
Package server contains internal server-side functionality used by the public facing xds package.
Package server contains internal server-side functionality used by the public facing xds package.
internal/test/e2e
Package e2e implements xds e2e tests using go-control-plane.
Package e2e implements xds e2e tests using go-control-plane.
internal/testutils
Package testutils provides utility types, for use in xds tests.
Package testutils provides utility types, for use in xds tests.
internal/testutils/fakeclient
Package fakeclient provides a fake implementation of an xDS client.
Package fakeclient provides a fake implementation of an xDS client.
internal/xdsclient
Package xdsclient implements a full fledged gRPC client for the xDS API used by the xds resolver and balancer implementations.
Package xdsclient implements a full fledged gRPC client for the xDS API used by the xds resolver and balancer implementations.
internal/xdsclient/internal
Package internal contains functionality internal to the xdsclient package.
Package internal contains functionality internal to the xdsclient package.
internal/xdsclient/load
Package load provides functionality to record and maintain load data.
Package load provides functionality to record and maintain load data.
internal/xdsclient/transport
Package transport defines the interface that describe the functionality required to communicate with an xDS server using streaming calls.
Package transport defines the interface that describe the functionality required to communicate with an xDS server using streaming calls.
internal/xdsclient/transport/ads
Package ads provides the implementation of an ADS (Aggregated Discovery Service) stream for the xDS client.
Package ads provides the implementation of an ADS (Aggregated Discovery Service) stream for the xDS client.
internal/xdsclient/transport/grpctransport
Package grpctransport provides an implementation of the transport interface using gRPC.
Package grpctransport provides an implementation of the transport interface using gRPC.
internal/xdsclient/transport/lrs
Package lrs provides the implementation of an LRS (Load Reporting Service) stream for the xDS client.
Package lrs provides the implementation of an LRS (Load Reporting Service) stream for the xDS client.
internal/xdsclient/xdslbregistry
Package xdslbregistry provides a registry of converters that convert proto from load balancing configuration, defined by the xDS API spec, to JSON load balancing configuration.
Package xdslbregistry provides a registry of converters that convert proto from load balancing configuration, defined by the xDS API spec, to JSON load balancing configuration.
internal/xdsclient/xdslbregistry/converter
Package converter provides converters to convert proto load balancing configuration, defined by the xDS API spec, to JSON load balancing configuration.
Package converter provides converters to convert proto load balancing configuration, defined by the xDS API spec, to JSON load balancing configuration.
internal/xdsclient/xdsresource
Package xdsresource implements the xDS data model layer.
Package xdsresource implements the xDS data model layer.
internal/xdsclient/xdsresource/version
Package version defines constants to distinguish between supported xDS API versions.
Package version defines constants to distinguish between supported xDS API versions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp