Search and commands

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

Type to search packages.

grpc

v1.10.0
github.com/teo/grpc-go

Documentation

pkg.go.dev ↗

Table of contents

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

134 matches

Top ↑

Package grpc implements an RPC system called gRPC.

See grpc.io for more information about gRPC.

Constants

SupportPackageIsVersion3 (3 declarations)

const (
	SupportPackageIsVersion3 = true
	SupportPackageIsVersion4 = true
	SupportPackageIsVersion5 = true
)

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

Older versions are kept for compatibility. They may be removed if compatibility cannot be maintained.

These constants should not be referenced from any other code.

PickFirstBalancerName

const PickFirstBalancerName = "pick_first"

PickFirstBalancerName is the name of the pick_first balancer.

Version

const Version = "1.10.0"

Version is the current grpc version.

Variables

DefaultBackoffConfig

var DefaultBackoffConfig = BackoffConfig{
	MaxDelay: 120 * time.Second,
	// contains filtered or unexported fields
}

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

EnableTracing

var EnableTracing bool

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

ErrClientConnClosing

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")
)

ErrClientConnTimeout

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

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

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

ErrServerStopped

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

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

Functions

Code

func Code(err error) codes.Code

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

Deprecated: use status.FromError and Code method instead.

ErrorDesc

func ErrorDesc(err error) string

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

Deprecated: use status.FromError and Message method instead.

Errorf

func Errorf(c codes.Code, format string, a ...interface{}) error

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

Deprecated: use status.Errorf instead.

Invoke

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

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

DEPRECATED: Use ClientConn.Invoke instead.

MethodFromServerStream

func MethodFromServerStream(stream ServerStream) (string, bool)

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

NewLBBuilderWithFallbackTimeout

func NewLBBuilderWithFallbackTimeout(fallbackTimeout time.Duration) balancer.Builder

NewLBBuilderWithFallbackTimeout creates a grpclb builder with the given fallbackTimeout. If no response is received from the remote balancer within fallbackTimeout, the backend addresses from the resolved address list will be used.

Only call this function when a non-default fallback timeout is needed.

SendHeader

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

SendHeader sends header metadata. It may be called at most once. The provided md and headers set by SetHeader() will be sent.

SetHeader

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

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

  • grpc.SendHeader() is called;
  • The first response is sent out;
  • An RPC status is sent out (error or success).

SetTrailer

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

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

Types

Address

type Address struct {
	// Addr is the server address on which a connection will be established.
	Addr string
	// Metadata is the information associated with Addr, which may be used
	// to make load balancing decision.
	Metadata interface{}
}

Address represents a server the client connects to. This is the EXPERIMENTAL API and may be changed or extended in the future.

BackoffConfig

type BackoffConfig struct {
	// MaxDelay is the upper bound of backoff delay.
	MaxDelay time.Duration
	// contains filtered or unexported fields
}

BackoffConfig defines the parameters for the default gRPC backoff strategy.

Balancer

type Balancer interface {
	// Start does the initialization work to bootstrap a Balancer. For example,
	// this function may start the name resolution and watch the updates. It will
	// be called when dialing.
	Start(target string, config BalancerConfig) error
	// Up informs the Balancer that gRPC has a connection to the server at
	// addr. It returns down which is called once the connection to addr gets
	// lost or closed.
	// TODO: It is not clear how to construct and take advantage of the meaningful error
	// parameter for down. Need realistic demands to guide.
	Up(addr Address) (down func(error))
	// Get gets the address of a server for the RPC corresponding to ctx.
	// i) If it returns a connected address, gRPC internals issues the RPC on the
	// connection to this address;
	// ii) If it returns an address on which the connection is under construction
	// (initiated by Notify(...)) but not connected, gRPC internals
	//  * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or
	//  Shutdown state;
	//  or
	//  * issues RPC on the connection otherwise.
	// iii) If it returns an address on which the connection does not exist, gRPC
	// internals treats it as an error and will fail the corresponding RPC.
	//
	// Therefore, the following is the recommended rule when writing a custom Balancer.
	// If opts.BlockingWait is true, it should return a connected address or
	// block if there is no connected address. It should respect the timeout or
	// cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast
	// RPCs), it should return an address it has notified via Notify(...) immediately
	// instead of blocking.
	//
	// The function returns put which is called once the rpc has completed or failed.
	// put can collect and report RPC stats to a remote load balancer.
	//
	// This function should only return the errors Balancer cannot recover by itself.
	// gRPC internals will fail the RPC if an error is returned.
	Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error)
	// Notify returns a channel that is used by gRPC internals to watch the addresses
	// gRPC needs to connect. The addresses might be from a name resolver or remote
	// load balancer. gRPC internals will compare it with the existing connected
	// addresses. If the address Balancer notified is not in the existing connected
	// addresses, gRPC starts to connect the address. If an address in the existing
	// connected addresses is not in the notification list, the corresponding connection
	// is shutdown gracefully. Otherwise, there are no operations to take. Note that
	// the Address slice must be the full list of the Addresses which should be connected.
	// It is NOT delta.
	Notify() <-chan []Address
	// Close shuts down the balancer.
	Close() error
}

Balancer chooses network addresses for RPCs. This is the EXPERIMENTAL API and may be changed or extended in the future.

RoundRobin

func RoundRobin(r naming.Resolver) Balancer

RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch the name resolution updates and updates the addresses available correspondingly.

BalancerConfig

type BalancerConfig struct {
	// DialCreds is the transport credential the Balancer implementation can
	// use to dial to a remote load balancer server. The Balancer implementations
	// can ignore this if it does not need to talk to another party securely.
	DialCreds credentials.TransportCredentials
	// Dialer is the custom dialer the Balancer implementation can use to dial
	// to a remote load balancer server. The Balancer implementations
	// can ignore this if it doesn't need to talk to remote balancer.
	Dialer func(context.Context, string) (net.Conn, error)
}

BalancerConfig specifies the configurations for Balancer.

BalancerGetOptions

type BalancerGetOptions struct {
	// BlockingWait specifies whether Get should block when there is no
	// connected address.
	BlockingWait bool
}

BalancerGetOptions configures a Get call. This is the EXPERIMENTAL API and may be changed or extended in the future.

CallOption

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

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

CallContentSubtype

func CallContentSubtype(contentSubtype string) CallOption

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

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

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

CallCustomCodec

func CallCustomCodec(codec Codec) CallOption

CallCustomCodec returns a CallOption that will set the given Codec to be used for all request and response messages for a call. The result of calling String() will be used as the content-subtype in a case-insensitive manner.

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

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

FailFast

func FailFast(failFast bool) CallOption

FailFast configures the action to take when an RPC is attempted on broken connections or unreachable servers. If failFast is true, the RPC will fail immediately. Otherwise, the RPC client will block the call until a connection is available (or the call is canceled or times out) and will retry the call if it fails due to a transient error. gRPC will not retry if data was written to the wire unless the server indicates it did not process the data. Please refer to https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.

By default, RPCs are "Fail Fast".

Header

func Header(md *metadata.MD) CallOption

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

MaxCallRecvMsgSize

func MaxCallRecvMsgSize(s int) CallOption

MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive.

MaxCallSendMsgSize

func MaxCallSendMsgSize(s int) CallOption

MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send.

Peer

func Peer(p *peer.Peer) CallOption

Peer returns a CallOption that retrieves peer information for a unary RPC.

PerRPCCredentials

func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption

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

Trailer

func Trailer(md *metadata.MD) CallOption

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

UseCompressor

func UseCompressor(name string) CallOption

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

This API is EXPERIMENTAL.

ClientConn

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

ClientConn represents a client connection to an RPC server.

Dial

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

Dial creates a client connection to the given target.

DialContext

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

DialContext creates a client connection to the given target. ctx can be used to cancel or expire the pending connection. Once this function returns, the cancellation and expiration of ctx will be noop. Users should call ClientConn.Close to terminate all the pending operations after this function returns.

The target name syntax is defined in https://github.com/grpc/grpc/blob/master/doc/naming.md. e.g. to use dns resolver, a "dns:///" prefix should be applied to the target.

ClientConn.Close

func (cc *ClientConn) Close() error

Close tears down the ClientConn and all underlying connections.

ClientConn.GetMethodConfig

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

GetMethodConfig gets the method config of the input method. If there's an exact match for input method (i.e. /service/method), we return the corresponding MethodConfig. If there isn't an exact match for the input method, we look for the default config under the service (i.e /service/). If there is a default MethodConfig for the serivce, we return it. Otherwise, we return an empty MethodConfig.

ClientConn.GetState

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

GetState returns the connectivity.State of ClientConn. This is an EXPERIMENTAL API.

ClientConn.Invoke

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

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

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

ClientConn.NewStream

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

NewStream creates a new Stream for the client side. This is typically called by generated code.

ClientConn.WaitForStateChange

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

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

ClientStream

type ClientStream interface {
	// Header returns the header metadata received from the server if there
	// is any. It blocks if the metadata is not ready to read.
	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.
	CloseSend() error
	// Stream.SendMsg() may return a non-nil error when something wrong happens sending
	// the request. The returned error indicates the status of this sending, not the final
	// status of the RPC.
	//
	// Always call Stream.RecvMsg() to drain the stream and get the final
	// status, otherwise there could be leaked resources.
	Stream
}

ClientStream defines the interface a client stream has to satisfy.

NewClientStream

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

NewClientStream creates a new Stream for the client side. This is typically called by generated code.

DEPRECATED: Use ClientConn.NewStream instead.

Codec

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

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

Deprecated: use encoding.Codec instead.

Compressor

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

Compressor defines the interface gRPC uses to compress a message.

NewGZIPCompressor

func NewGZIPCompressor() Compressor

NewGZIPCompressor creates a Compressor based on GZIP.

Decompressor

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

Decompressor defines the interface gRPC uses to decompress a message.

NewGZIPDecompressor

func NewGZIPDecompressor() Decompressor

NewGZIPDecompressor creates a Decompressor based on GZIP.

DialOption

type DialOption func(*dialOptions)

DialOption configures how we set up the connection.

FailOnNonTempDialError

func FailOnNonTempDialError(f bool) DialOption

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

WithAuthority

func WithAuthority(a string) DialOption

WithAuthority returns a DialOption that specifies the value to be used as the :authority pseudo-header. This value only works with WithInsecure and has no effect if TransportCredentials are present.

WithBackoffConfig

func WithBackoffConfig(b BackoffConfig) DialOption

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

Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up for use.

WithBackoffMaxDelay

func WithBackoffMaxDelay(md time.Duration) DialOption

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

WithBalancer

func WithBalancer(b Balancer) DialOption

WithBalancer returns a DialOption which sets a load balancer with the v1 API. Name resolver will be ignored if this DialOption is specified.

Deprecated: use the new balancer APIs in balancer package and WithBalancerName.

WithBalancerName

func WithBalancerName(balancerName string) DialOption

WithBalancerName sets the balancer that the ClientConn will be initialized with. Balancer registered with balancerName will be used. This function panics if no balancer was registered by balancerName.

The balancer cannot be overridden by balancer option specified by service config.

This is an EXPERIMENTAL API.

WithBlock

func WithBlock() DialOption

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

WithCodec

func WithCodec(c Codec) DialOption

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

Deprecated: use WithDefaultCallOptions(CallCustomCodec(c)) instead.

WithCompressor

func WithCompressor(cp Compressor) DialOption

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

Deprecated: use UseCompressor instead.

WithDecompressor

func WithDecompressor(dc Decompressor) DialOption

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

Deprecated: use encoding.RegisterCompressor instead.

WithDefaultCallOptions

func WithDefaultCallOptions(cos ...CallOption) DialOption

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

WithDialer

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

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

WithInitialConnWindowSize

func WithInitialConnWindowSize(s int32) DialOption

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

WithInitialWindowSize

func WithInitialWindowSize(s int32) DialOption

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

WithInsecure

func WithInsecure() DialOption

WithInsecure returns a DialOption which disables transport security for this ClientConn. Note that transport security is required unless WithInsecure is set.

WithKeepaliveParams

func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption

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

WithMaxMsgSize

func WithMaxMsgSize(s int) DialOption

WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive. Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead.

WithPerRPCCredentials

func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption

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

WithReadBufferSize

func WithReadBufferSize(s int) DialOption

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

WithServiceConfig

func WithServiceConfig(c <-chan ServiceConfig) DialOption

WithServiceConfig returns a DialOption which has a channel to read the service configuration. DEPRECATED: service config should be received through name resolver, as specified here. https://github.com/grpc/grpc/blob/master/doc/service_config.md

WithStatsHandler

func WithStatsHandler(h stats.Handler) DialOption

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

WithStreamInterceptor

func WithStreamInterceptor(f StreamClientInterceptor) DialOption

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

WithTimeout

func WithTimeout(d time.Duration) DialOption

WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn initially. This is valid if and only if WithBlock() is present. Deprecated: use DialContext and context.WithTimeout instead.

WithTransportCredentials

func WithTransportCredentials(creds credentials.TransportCredentials) DialOption

WithTransportCredentials returns a DialOption which configures a connection level security credentials (e.g., TLS/SSL).

WithUnaryInterceptor

func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption

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

WithUserAgent

func WithUserAgent(s string) DialOption

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

WithWaitForHandshake

func WithWaitForHandshake() DialOption

WithWaitForHandshake blocks until the initial settings frame is received from the server before assigning RPCs to the connection. Experimental API.

WithWriteBufferSize

func WithWriteBufferSize(s int) DialOption

WithWriteBufferSize lets you set the size of write buffer, this determines how much data can be batched before doing a write on the wire.

EmptyCallOption

type EmptyCallOption struct{}

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

MethodConfig

type MethodConfig struct {
	// WaitForReady indicates whether RPCs sent to this method should wait until
	// the connection is ready by default (!failfast). The value specified via the
	// gRPC client API will override the value set here.
	WaitForReady *bool
	// Timeout is the default timeout for RPCs sent to this method. The actual
	// deadline used will be the minimum of the value specified here and the value
	// set by the application via the gRPC client API.  If either one is not set,
	// then the other will be used.  If neither is set, then the RPC has no deadline.
	Timeout *time.Duration
	// MaxReqSize is the maximum allowed payload size for an individual request in a
	// stream (client->server) in bytes. The size which is measured is the serialized
	// payload after per-message compression (but before stream compression) in bytes.
	// The actual value used is the minimum of the value specified here and the value set
	// by the application via the gRPC client API. If either one is not set, then the other
	// will be used.  If neither is set, then the built-in default is used.
	MaxReqSize *int
	// MaxRespSize is the maximum allowed payload size for an individual response in a
	// stream (server->client) in bytes.
	MaxRespSize *int
}

MethodConfig defines the configuration recommended by the service providers for a particular method. DEPRECATED: Users should not use this struct. Service config should be received through name resolver, as specified here https://github.com/grpc/grpc/blob/master/doc/service_config.md

MethodDesc

type MethodDesc struct {
	MethodName string
	Handler    methodHandler
}

MethodDesc represents an RPC service's method specification.

MethodInfo

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

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

Server

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

Server is a gRPC server to serve RPC requests.

NewServer

func NewServer(opt ...ServerOption) *Server

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

Server.GetServiceInfo

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

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

Server.GracefulStop

func (s *Server) GracefulStop()

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

Server.RegisterService

func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})

RegisterService registers a service and its implementation to the gRPC server. It is called from the IDL generated code. This must be called before invoking Serve.

Server.Serve

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

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

Server.ServeHTTP

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

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

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

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

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

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

Server.Stop

func (s *Server) Stop()

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

ServerOption

type ServerOption func(*options)

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

ConnectionTimeout

func ConnectionTimeout(d time.Duration) ServerOption

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

This API is EXPERIMENTAL.

Creds

func Creds(c credentials.TransportCredentials) ServerOption

Creds returns a ServerOption that sets credentials for server connections.

CustomCodec

func CustomCodec(codec Codec) ServerOption

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

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

InTapHandle

func InTapHandle(h tap.ServerInHandle) ServerOption

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

InitialConnWindowSize

func InitialConnWindowSize(s int32) ServerOption

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

InitialWindowSize

func InitialWindowSize(s int32) ServerOption

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

KeepaliveEnforcementPolicy

func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption

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

KeepaliveParams

func KeepaliveParams(kp keepalive.ServerParameters) ServerOption

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

MaxConcurrentStreams

func MaxConcurrentStreams(n uint32) ServerOption

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

MaxMsgSize

func MaxMsgSize(m int) ServerOption

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

MaxRecvMsgSize

func MaxRecvMsgSize(m int) ServerOption

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

MaxSendMsgSize

func MaxSendMsgSize(m int) ServerOption

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

RPCCompressor

func RPCCompressor(cp Compressor) ServerOption

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

Deprecated: use encoding.RegisterCompressor instead.

RPCDecompressor

func RPCDecompressor(dc Decompressor) ServerOption

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

Deprecated: use encoding.RegisterCompressor instead.

ReadBufferSize

func ReadBufferSize(s int) ServerOption

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

StatsHandler

func StatsHandler(h stats.Handler) ServerOption

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

StreamInterceptor

func StreamInterceptor(i StreamServerInterceptor) ServerOption

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

UnaryInterceptor

func UnaryInterceptor(i UnaryServerInterceptor) ServerOption

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

UnknownServiceHandler

func UnknownServiceHandler(streamHandler StreamHandler) ServerOption

UnknownServiceHandler returns a ServerOption that allows for adding a custom unknown service handler. The provided method is a bidi-streaming RPC service handler that will be invoked instead of returning the "unimplemented" gRPC error whenever a request is received for an unregistered service or method. The handling function has full access to the Context of the request and the stream, and the invocation bypasses interceptors.

WriteBufferSize

func WriteBufferSize(s int) ServerOption

WriteBufferSize lets you set the size of write buffer, this determines how much data can be batched before doing a write on the wire.

ServerStream

type ServerStream interface {
	// SetHeader sets the header metadata. It may be called multiple times.
	// When call multiple times, all the provided metadata will be merged.
	// All the metadata will be sent out when one of the following happens:
	//  - ServerStream.SendHeader() is called;
	//  - The first response is sent out;
	//  - An RPC status is sent out (error or success).
	SetHeader(metadata.MD) error
	// SendHeader sends the header metadata.
	// The provided md and headers set by SetHeader() will be sent.
	// It fails if called multiple times.
	SendHeader(metadata.MD) error
	// SetTrailer sets the trailer metadata which will be sent with the RPC status.
	// When called more than once, all the provided metadata will be merged.
	SetTrailer(metadata.MD)
	Stream
}

ServerStream defines the interface a server stream has to satisfy.

ServiceConfig

type ServiceConfig struct {
	// LB is the load balancer the service providers recommends. The balancer specified
	// via grpc.WithBalancer will override this.
	LB *string
	// 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
}

ServiceConfig is provided by the service provider and contains parameters for how clients that connect to the service should behave. DEPRECATED: Users should not use this struct. Service config should be received through name resolver, as specified here https://github.com/grpc/grpc/blob/master/doc/service_config.md

ServiceDesc

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

ServiceDesc represents an RPC service's specification.

ServiceInfo

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

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

Stream

type Stream interface {
	// Context returns the context for this stream.
	Context() context.Context
	// SendMsg blocks until it sends m, the stream is done or the stream
	// breaks.
	// On error, it aborts the stream and returns an RPC status on client
	// side. On server side, it simply returns the error to the caller.
	// SendMsg is called by generated code. Also Users can call SendMsg
	// directly when it is really needed in their use cases.
	// It's 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.
	SendMsg(m interface{}) error
	// RecvMsg blocks until it receives a message or the stream is
	// done. On client side, it returns io.EOF when the stream is done. On
	// any other error, it aborts the stream and returns an RPC status. On
	// server side, it simply returns the error to the caller.
	// It's safe to have a goroutine calling SendMsg and another goroutine calling
	// recvMsg on the same stream at the same time.
	// But it is not safe to call RecvMsg on the same stream in different goroutines.
	RecvMsg(m interface{}) error
}

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

All errors returned from Stream are compatible with the status package.

StreamClientInterceptor

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

StreamClientInterceptor intercepts the creation of ClientStream. It may return a custom ClientStream to intercept all I/O operations. streamer is the handler to create a ClientStream and it is the responsibility of the interceptor to call it. This is an EXPERIMENTAL API.

StreamDesc

type StreamDesc struct {
	StreamName string
	Handler    StreamHandler

	// At least one of these is true.
	ServerStreams bool
	ClientStreams bool
}

StreamDesc represents a streaming RPC service's method specification.

StreamHandler

type StreamHandler func(srv interface{}, stream ServerStream) error

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

StreamServerInfo

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

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

StreamServerInterceptor

type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) 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 the service method implementation. It is the responsibility of the interceptor to invoke handler to complete the RPC.

Streamer

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

Streamer is called by StreamClientInterceptor to create a ClientStream.

UnaryClientInterceptor

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

UnaryClientInterceptor intercepts the execution of a unary RPC on the client. invoker is the handler to complete the RPC and it is the responsibility of the interceptor to call it. This is an EXPERIMENTAL API.

UnaryHandler

type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error)

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

UnaryInvoker

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

UnaryInvoker is called by UnaryClientInterceptor to complete RPCs.

UnaryServerInfo

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

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

UnaryServerInterceptor

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

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

Dependency graph