Categorygoogle.golang.org/grpc
modulepackage
1.72.0-dev
Repository: https://github.com/grpc/grpc-go.git
Documentation: pkg.go.dev

# README

gRPC-Go

GoDoc GoReportCard codecov

The Go implementation of gRPC: A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the Go gRPC docs, or jump directly into the quick start.

Prerequisites

Installation

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

import "google.golang.org/grpc"

Note: If you are trying to access grpc-go from China, see the FAQ below.

Learn more

FAQ

I/O Timeout Errors

The golang.org domain may be blocked from some countries. go get usually produces an error like the following when this happens:

$ go get -u google.golang.org/grpc
package 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 the replace feature of go 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@latest
    go mod tidy
    go mod vendor
    go build -mod=vendor
    

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

Compiling error, undefined: grpc.SupportPackageIsVersion

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

How to turn on logging

The default logger is controlled by environment variables. Turn everything on like 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 many possible 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 have configured your server to terminate connections regularly to trigger DNS lookups. If this is the case, you may want to increase your MaxConnectionAgeGrace, to allow longer RPC calls to finish.

It can be tricky to debug this because the error happens on the client side but the root cause of the connection being closed is on the server side. Turn on logging on both client and server, and see if there are any transport errors.

# Packages

Package admin provides a convenient method for registering a collection of administration services to a gRPC server.
Package attributes defines a generic key/value store used in various gRPC components.
Package authz exposes methods to manage authorization within gRPC.
Package backoff provides configuration options for backoff.
Package balancer defines APIs for load balancing in gRPC.
Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks.
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 codes defines the canonical error codes used by gRPC.
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 encoding defines the interface for the compressor and codec, and functions to register and retrieve compressors and codecs.
Package experimental is a collection of experimental features that might have some rough edges to them.
Package grpclog defines logging for grpc.
Package health provides a service that exposes server's health and it must be imported to enable support for client-side health checks.
Package interop contains functions used by interop client/server.
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 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 peer defines various peer information associated with RPCs and corresponding utils.
Package profiling exposes methods to manage profiling within gRPC.
Package reflection implements server reflection service.
Package resolver defines APIs for name resolution in gRPC.
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 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 test contains tests.
Package xds contains an implementation of the xDS suite of protocols, to be used by gRPC client and server applications.

# Functions

CallContentSubtype returns a CallOption that will set the content-subtype for a call.
CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of an encoding.Codec.
ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor for streaming RPCs.
ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor for unary RPCs.
ClientSupportedCompressors returns compressor names advertised by the client via grpc-accept-encoding header.
Code returns the error code for err if it was produced by the rpc system.
ConnectionTimeout returns a ServerOption that sets the timeout for connection establishment (up to and including HTTP/2 handshaking) for all new connections.
Creds returns a ServerOption that sets credentials for server connections.
CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
Dial calls DialContext(context.Background(), target, opts...).
DialContext calls NewClient and then exits idle mode.
ErrorDesc returns the error description of err if it was produced by the rpc system.
Errorf returns an error containing an error code and a description; Errorf returns nil if c is OK.
FailFast is the opposite of WaitForReady.
FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on non-temporary dial errors.
ForceCodec returns a CallOption that will set codec to be used for all request and response messages for a call.
ForceCodecV2 returns a CallOption that will set codec to be used for all request and response messages for a call.
ForceServerCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
ForceServerCodecV2 is the equivalent of ForceServerCodec, but for the new CodecV2 interface.
Header returns a CallOptions that retrieves the header metadata for a unary RPC.
HeaderTableSize returns a ServerOption that sets the size of dynamic header table for stream.
InitialConnWindowSize returns a ServerOption that sets window size for a connection.
InitialWindowSize returns a ServerOption that sets window size for stream.
InTapHandle returns a ServerOption that sets the tap handle for all the server transport to be created.
Invoke sends the RPC request on the wire and returns after response is received.
KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server.
KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.
MaxCallRecvMsgSize returns a CallOption which sets the maximum message size in bytes the client can receive.
MaxCallSendMsgSize returns a CallOption which sets the maximum message size in bytes the client can send.
MaxConcurrentStreams returns a ServerOption that will apply a limit on the number of concurrent streams to each ServerTransport.
MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size of header list that the server is prepared to accept.
MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory used for buffering this RPC's requests for retry purposes.
MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send.
Method returns the method string for the server context.
MethodFromServerStream returns the method string for the input stream.
NewClient creates a new gRPC "channel" for the target URI provided.
NewClientStream is a wrapper for ClientConn.NewStream.
NewContextWithServerTransportStream creates a new context from ctx and attaches stream to it.
NewGZIPCompressor creates a Compressor based on GZIP.
NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead of assuming DefaultCompression.
NewGZIPDecompressor creates a Decompressor based on GZIP.
NewServer creates a gRPC server which has no service registered and has not started to accept requests yet.
NumStreamWorkers returns a ServerOption that sets the number of worker goroutines that should be used to process incoming streams.
OnFinish returns a CallOption that configures a callback to be called when the call completes.
Peer returns a CallOption that retrieves peer information for a unary RPC.
PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials for a call.
ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most for one read syscall.
RPCCompressor returns a ServerOption that sets a compressor for outbound messages.
RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages.
SendHeader sends header metadata.
ServerTransportStreamFromContext returns the ServerTransportStream saved in ctx.
SetHeader sets the header metadata to be sent from the server to the client.
SetSendCompressor sets a compressor for outbound messages from the server.
SetTrailer sets the trailer metadata that will be sent when an RPC returns.
SharedWriteBuffer allows reusing per-connection transport write buffer.
StaticMethod returns a CallOption which specifies that a call is being made to a method that is static, which means the method is known at compile time and doesn't change at runtime.
StatsHandler returns a ServerOption that sets the stats handler for the server.
StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the server.
Trailer returns a CallOptions that retrieves the trailer metadata for a unary RPC.
UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the server.
UnknownServiceHandler returns a ServerOption that allows for adding a custom unknown service handler.
UseCompressor returns a CallOption which sets the compressor used when sending the request.
WaitForHandlers cause Stop to wait until all outstanding method handlers have exited before returning.
WaitForReady configures the RPC's behavior when the client is in TRANSIENT_FAILURE, which occurs when all addresses fail to connect.
WithAuthority returns a DialOption that specifies the value to be used as the :authority pseudo-header and as the server name in authentication handshake.
WithBackoffConfig configures the dialer to use the provided backoff parameters after connection failures.
WithBackoffMaxDelay configures the dialer to use the provided maximum delay when backing off after failed connection attempts.
WithBlock returns a DialOption which makes callers of Dial block until the underlying connection is up.
WithChainStreamInterceptor returns a DialOption that specifies the chained interceptor for streaming RPCs.
WithChainUnaryInterceptor returns a DialOption that specifies the chained interceptor for unary RPCs.
WithChannelzParentID returns a DialOption that specifies the channelz ID of current ClientConn's parent.
WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.
WithCompressor returns a DialOption which sets a Compressor to use for message compression.
WithConnectParams configures the ClientConn to use the provided ConnectParams for creating and maintaining connections to servers.
WithContextDialer returns a DialOption that sets a dialer to create connections.
WithCredentialsBundle returns a DialOption to set a credentials bundle for the ClientConn.WithCreds.
WithDecompressor returns a DialOption which sets a Decompressor to use for incoming message decompression.
WithDefaultCallOptions returns a DialOption which sets the default CallOptions for calls over the connection.
WithDefaultServiceConfig returns a DialOption that configures the default service config, which will be used in cases where: 1.
WithDialer returns a DialOption that specifies a function to use for dialing network addresses.
WithDisableHealthCheck disables the LB channel health checking for all SubConns of this ClientConn.
WithDisableRetry returns a DialOption that disables retries, even if the service config enables them.
WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any service config provided by the resolver and provides a hint to the resolver to not fetch service configs.
WithIdleTimeout returns a DialOption that configures an idle timeout for the channel.
WithInitialConnWindowSize returns a DialOption which sets the value for initial window size on a connection.
WithInitialWindowSize returns a DialOption which sets the value for initial window size on a stream.
WithInsecure returns a DialOption which disables transport security for this ClientConn.
WithKeepaliveParams returns a DialOption that specifies keepalive parameters for the client transport.
WithLocalDNSResolution forces local DNS name resolution even when a proxy is specified in the environment.
WithMaxCallAttempts returns a DialOption that configures the maximum number of attempts per call (including retries and hedging) using the channel.
WithMaxHeaderListSize returns a DialOption that specifies the maximum (uncompressed) size of header list that the client is prepared to accept.
WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive.
WithNoProxy returns a DialOption which disables the use of proxies for this ClientConn.
WithPerRPCCredentials returns a DialOption which sets credentials and places auth state on each outbound RPC.
WithReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most for each read syscall.
WithResolvers allows a list of resolver implementations to be registered locally with the ClientConn without needing to be globally registered via resolver.Register.
WithReturnConnectionError returns a DialOption which makes the client connection return a string containing both the last connection error that occurred and the context.DeadlineExceeded error.
WithSharedWriteBuffer allows reusing per-connection transport write buffer.
WithStatsHandler returns a DialOption that specifies the stats handler for all the RPCs and underlying network connections in this ClientConn.
WithStreamInterceptor returns a DialOption that specifies the interceptor for streaming RPCs.
WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn initially.
WithTransportCredentials returns a DialOption which configures a connection level security credentials (e.g., TLS/SSL).
WithUnaryInterceptor returns a DialOption that specifies the interceptor for unary RPCs.
WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.
WithWriteBufferSize determines how much data can be batched before doing a write on the wire.
WriteBufferSize determines how much data can be batched before doing a write on the wire.

# Constants

The SupportPackageIsVersion variables are referenced from generated protocol buffer files to ensure compatibility with the gRPC version used.
The SupportPackageIsVersion variables are referenced from generated protocol buffer files to ensure compatibility with the gRPC version used.
The SupportPackageIsVersion variables are referenced from generated protocol buffer files to ensure compatibility with the gRPC version used.
The SupportPackageIsVersion variables are referenced from generated protocol buffer files to ensure compatibility with the gRPC version used.
The SupportPackageIsVersion variables are referenced from generated protocol buffer files to ensure compatibility with the gRPC version used.
The SupportPackageIsVersion variables are referenced from generated protocol buffer files to ensure compatibility with the gRPC version used.
The SupportPackageIsVersion variables are referenced from generated protocol buffer files to ensure compatibility with the gRPC version used.
Version is the current grpc version.

# Variables

DefaultBackoffConfig uses values specified for backoff in https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package.
ErrClientConnClosing indicates that the operation is illegal because the ClientConn is closing.
ErrClientConnTimeout indicates that the ClientConn cannot establish the underlying connections within the specified timeout.
ErrServerStopped indicates that the operation is now illegal because of the server being stopped.
PickFirstBalancerName is the name of the pick_first balancer.

# Structs

BackoffConfig defines the parameters for the default gRPC backoff strategy.
ClientConn represents a virtual connection to a conceptual endpoint, to perform RPCs.
CompressorCallOption is a CallOption that indicates the compressor to use.
ConnectParams defines the parameters for connecting and retrying.
ContentSubtypeCallOption is a CallOption that indicates the content-subtype used for marshaling messages.
CustomCodecCallOption is a CallOption that indicates the codec used for marshaling messages.
EmptyCallOption does not alter the Call configuration.
EmptyDialOption does not alter the dial configuration.
EmptyServerOption does not alter the server configuration.
FailFastCallOption is a CallOption for indicating whether an RPC should fail fast or not.
ForceCodecCallOption is a CallOption that indicates the codec used for marshaling messages.
ForceCodecV2CallOption is a CallOption that indicates the codec used for marshaling messages.
GenericClientStream implements the ServerStreamingClient, ClientStreamingClient, and BidiStreamingClient interfaces.
GenericServerStream implements the ServerStreamingServer, ClientStreamingServer, and BidiStreamingServer interfaces.
HeaderCallOption is a CallOption for collecting response header metadata.
MaxHeaderListSizeDialOption is a DialOption that specifies the maximum (uncompressed) size of header list that the client is prepared to accept.
MaxHeaderListSizeServerOption is a ServerOption that sets the max (uncompressed) size of header list that the server is prepared to accept.
MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message size in bytes the client can receive.
MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of memory to be used for caching this RPC for retry purposes.
MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message size in bytes the client can send.
MethodDesc represents an RPC service's method specification.
MethodInfo contains the information of an RPC including its method name and type.
OnFinishCallOption is CallOption that indicates a callback to be called when the call completes.
PeerCallOption is a CallOption for collecting the identity of the remote peer.
PerRPCCredsCallOption is a CallOption that indicates the per-RPC credentials to use for the call.
PreparedMsg is responsible for creating a Marshalled and Compressed object.
Server is a gRPC server to serve RPC requests.
ServiceConfig is provided by the service provider and contains parameters for how clients that connect to the service should behave.
ServiceDesc represents an RPC service's specification.
ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service.
StaticMethodCallOption is a CallOption that specifies that a call comes from a static method.
StreamDesc represents a streaming RPC service's method specification.
StreamServerInfo consists of various information about a streaming RPC on server side.
TrailerCallOption is a CallOption for collecting response trailer metadata.
UnaryServerInfo consists of various information about a unary RPC on server side.

# Interfaces

BidiStreamingClient represents the client side of a bidirectional-streaming (many requests, many responses) RPC.
BidiStreamingServer represents the server side of a bidirectional-streaming (many requests, many responses) RPC.
CallOption configures a Call before it starts or extracts information from a Call after it completes.
ClientConnInterface defines the functions clients need to perform unary and streaming RPCs.
ClientStream defines the client-side behavior of a streaming RPC.
ClientStreamingClient represents the client side of a client-streaming (many requests, one response) RPC.
ClientStreamingServer represents the server side of a client-streaming (many requests, one response) RPC.
Codec defines the interface gRPC uses to encode and decode messages.
Compressor defines the interface gRPC uses to compress a message.
Decompressor defines the interface gRPC uses to decompress a message.
DialOption configures how we set up the connection.
A ServerOption sets options such as credentials, codec and keepalive parameters, etc.
ServerStream defines the server-side behavior of a streaming RPC.
ServerStreamingClient represents the client side of a server-streaming (one request, many responses) RPC.
ServerStreamingServer represents the server side of a server-streaming (one request, many responses) RPC.
ServerTransportStream is a minimal interface that a transport stream must implement.
ServiceRegistrar wraps a single method that supports service registration.
Stream defines the common interface a client or server stream has to satisfy.

# Type aliases

MethodConfig defines the configuration recommended by the service providers for a particular method.
MethodHandler is a function type that processes a unary RPC method call.
StreamClientInterceptor intercepts the creation of a ClientStream.
Streamer is called by StreamClientInterceptor to create a ClientStream.
StreamHandler defines the handler called by gRPC server to complete the execution of a streaming RPC.
StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server.
UnaryClientInterceptor intercepts the execution of a unary RPC on the client.
UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal execution of a unary RPC.
UnaryInvoker is called by UnaryClientInterceptor to complete RPCs.
UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server.