grpc - ActiveState ActiveGo 1.8
...

Package grpc

import "google.golang.org/grpc"
Overview
Index
Subdirectories

Overview ▾

Package grpc implements an RPC system called gRPC.

See www.grpc.io for more information about gRPC.

Index ▾

Constants
Variables
func Code(err error) codes.Code
func ErrorDesc(err error) string
func Errorf(c codes.Code, format string, a ...interface{}) error
func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error
func SendHeader(ctx context.Context, md metadata.MD) error
func SetHeader(ctx context.Context, md metadata.MD) error
func SetTrailer(ctx context.Context, md metadata.MD) error
type AddrMetadataGRPCLB
type Address
type AddressType
type BackoffConfig
type Balancer
    func NewGRPCLBBalancer(r naming.Resolver) Balancer
    func RoundRobin(r naming.Resolver) Balancer
type BalancerConfig
type BalancerGetOptions
type CallOption
    func FailFast(failFast bool) CallOption
    func Header(md *metadata.MD) CallOption
    func MaxCallRecvMsgSize(s int) CallOption
    func MaxCallSendMsgSize(s int) CallOption
    func Peer(peer *peer.Peer) CallOption
    func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption
    func Trailer(md *metadata.MD) CallOption
type ClientConn
    func Dial(target string, opts ...DialOption) (*ClientConn, error)
    func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error)
    func (cc *ClientConn) Close() error
    func (cc *ClientConn) GetMethodConfig(method string) MethodConfig
type ClientStream
    func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error)
type Codec
type Compressor
    func NewGZIPCompressor() Compressor
type ConnectivityState
    func (s ConnectivityState) String() string
type Decompressor
    func NewGZIPDecompressor() Decompressor
type DialOption
    func FailOnNonTempDialError(f bool) DialOption
    func WithAuthority(a string) DialOption
    func WithBackoffConfig(b BackoffConfig) DialOption
    func WithBackoffMaxDelay(md time.Duration) DialOption
    func WithBalancer(b Balancer) DialOption
    func WithBlock() DialOption
    func WithCodec(c Codec) DialOption
    func WithCompressor(cp Compressor) DialOption
    func WithDecompressor(dc Decompressor) DialOption
    func WithDefaultCallOptions(cos ...CallOption) DialOption
    func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption
    func WithInitialConnWindowSize(s int32) DialOption
    func WithInitialWindowSize(s int32) DialOption
    func WithInsecure() DialOption
    func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption
    func WithMaxMsgSize(s int) DialOption
    func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption
    func WithServiceConfig(c <-chan ServiceConfig) DialOption
    func WithStatsHandler(h stats.Handler) DialOption
    func WithStreamInterceptor(f StreamClientInterceptor) DialOption
    func WithTimeout(d time.Duration) DialOption
    func WithTransportCredentials(creds credentials.TransportCredentials) DialOption
    func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption
    func WithUserAgent(s string) DialOption
type EmptyCallOption
type MethodConfig
type MethodDesc
type MethodInfo
type Server
    func NewServer(opt ...ServerOption) *Server
    func (s *Server) GetServiceInfo() map[string]ServiceInfo
    func (s *Server) GracefulStop()
    func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})
    func (s *Server) Serve(lis net.Listener) error
    func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
    func (s *Server) Stop()
type ServerOption
    func Creds(c credentials.TransportCredentials) ServerOption
    func CustomCodec(codec Codec) ServerOption
    func InTapHandle(h tap.ServerInHandle) ServerOption
    func InitialConnWindowSize(s int32) ServerOption
    func InitialWindowSize(s int32) ServerOption
    func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption
    func KeepaliveParams(kp keepalive.ServerParameters) ServerOption
    func MaxConcurrentStreams(n uint32) ServerOption
    func MaxMsgSize(m int) ServerOption
    func MaxRecvMsgSize(m int) ServerOption
    func MaxSendMsgSize(m int) ServerOption
    func RPCCompressor(cp Compressor) ServerOption
    func RPCDecompressor(dc Decompressor) ServerOption
    func StatsHandler(h stats.Handler) ServerOption
    func StreamInterceptor(i StreamServerInterceptor) ServerOption
    func UnaryInterceptor(i UnaryServerInterceptor) ServerOption
    func UnknownServiceHandler(streamHandler StreamHandler) ServerOption
type ServerStream
type ServiceConfig
type ServiceDesc
type ServiceInfo
type Stream
type StreamClientInterceptor
type StreamDesc
type StreamHandler
type StreamServerInfo
type StreamServerInterceptor
type Streamer
type UnaryClientInterceptor
type UnaryHandler
type UnaryInvoker
type UnaryServerInfo
type UnaryServerInterceptor

Package files

backoff.go balancer.go call.go clientconn.go codec.go doc.go go17.go grpclb.go interceptor.go proxy.go rpc_util.go server.go stream.go trace.go

Constants

SupportPackageIsVersion4 is referenced from generated protocol buffer files to assert that that code is compatible with this version of the grpc package.

This constant may be renamed in the future if a change in the generated code requires a synchronised update of grpc-go and protoc-gen-go. This constant should not be referenced from any other code.

const SupportPackageIsVersion4 = true

Version is the current grpc version.

const Version = "1.4.1"

Variables

var (
    // ErrClientConnClosing indicates that the operation is illegal because
    // the ClientConn is closing.
    ErrClientConnClosing = errors.New("grpc: the client connection is closing")
    // ErrClientConnTimeout indicates that the ClientConn cannot establish the
    // underlying connections within the specified timeout.
    // DEPRECATED: Please use context.DeadlineExceeded instead.
    ErrClientConnTimeout = errors.New("grpc: timed out when dialing")
)

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

var (
    DefaultBackoffConfig = BackoffConfig{
        MaxDelay:  120 * time.Second,
        baseDelay: 1.0 * time.Second,
        factor:    1.6,
        jitter:    0.2,
    }
)

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.

var EnableTracing = true
var (
    // ErrServerStopped indicates that the operation is now illegal because of
    // the server being stopped.
    ErrServerStopped = errors.New("grpc: the server has been stopped")
)

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

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

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

func 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. Invoke is called by generated code. Also users can call Invoke directly when it is really needed in their use cases.

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

func 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).

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

type AddrMetadataGRPCLB

AddrMetadataGRPCLB contains the information the name resolver for grpclb should provide. The name resolver used by the grpclb balancer is required to provide this type of metadata in its address updates.

type AddrMetadataGRPCLB struct {
    // AddrType is the type of server (grpc load balancer or backend).
    AddrType AddressType
    // ServerName is the name of the grpc load balancer. Used for authentication.
    ServerName string
}

type Address

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

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{}
}

type AddressType

AddressType indicates the address type returned by name resolution.

type AddressType uint8
const (
    // Backend indicates the server is a backend server.
    Backend AddressType = iota
    // GRPCLB indicates the server is a grpclb load balancer.
    GRPCLB
)

type BackoffConfig

BackoffConfig defines the parameters for the default gRPC backoff strategy.

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

type Balancer

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

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
}

func NewGRPCLBBalancer

func NewGRPCLBBalancer(r naming.Resolver) Balancer

NewGRPCLBBalancer creates a grpclb load balancer.

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

type BalancerConfig

BalancerConfig specifies the configurations for Balancer.

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

type BalancerGetOptions

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

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

type CallOption

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

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

func 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. Please refer to https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md. Note: failFast is default to true.

func Header(md *metadata.MD) CallOption

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

func MaxCallRecvMsgSize

func MaxCallRecvMsgSize(s int) CallOption

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

func MaxCallSendMsgSize

func MaxCallSendMsgSize(s int) CallOption

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

func Peer

func Peer(peer *peer.Peer) CallOption

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

func PerRPCCredentials

func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption

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

func Trailer

func Trailer(md *metadata.MD) CallOption

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

type ClientConn

ClientConn represents a client connection to an RPC server.

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

func Dial

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

Dial creates a client connection to the given target.

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

func (*ClientConn) Close

func (cc *ClientConn) Close() error

Close tears down the ClientConn and all underlying connections.

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

type ClientStream

ClientStream defines the interface a client stream has to satisfy.

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
}

func NewClientStream

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

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

type Codec

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.

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. The returned
    // string will be used as part of content type in transmission.
    String() string
}

type Compressor

Compressor defines the interface gRPC uses to compress a message.

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
}

func NewGZIPCompressor

func NewGZIPCompressor() Compressor

NewGZIPCompressor creates a Compressor based on GZIP.

type ConnectivityState

ConnectivityState indicates the state of a client connection.

type ConnectivityState int
const (
    // Idle indicates the ClientConn is idle.
    Idle ConnectivityState = iota
    // Connecting indicates the ClienConn is connecting.
    Connecting
    // Ready indicates the ClientConn is ready for work.
    Ready
    // TransientFailure indicates the ClientConn has seen a failure but expects to recover.
    TransientFailure
    // Shutdown indicates the ClientConn has started shutting down.
    Shutdown
)

func (ConnectivityState) String

func (s ConnectivityState) String() string

type Decompressor

Decompressor defines the interface gRPC uses to decompress a message.

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
}

func NewGZIPDecompressor

func NewGZIPDecompressor() Decompressor

NewGZIPDecompressor creates a Decompressor based on GZIP.

type DialOption

DialOption configures how we set up the connection.

type DialOption func(*dialOptions)

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

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

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

func WithBackoffMaxDelay

func WithBackoffMaxDelay(md time.Duration) DialOption

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

func WithBalancer

func WithBalancer(b Balancer) DialOption

WithBalancer returns a DialOption which sets a load balancer.

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

func WithCodec

func WithCodec(c Codec) DialOption

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

func WithCompressor

func WithCompressor(cp Compressor) DialOption

WithCompressor returns a DialOption which sets a CompressorGenerator for generating message compressor.

func WithDecompressor

func WithDecompressor(dc Decompressor) DialOption

WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating message decompressor.

func WithDefaultCallOptions

func WithDefaultCallOptions(cos ...CallOption) DialOption

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

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

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

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

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

func WithKeepaliveParams

func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption

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

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

func WithPerRPCCredentials

func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption

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

func WithServiceConfig

func WithServiceConfig(c <-chan ServiceConfig) DialOption

WithServiceConfig returns a DialOption which has a channel to read the service configuration.

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

func WithStreamInterceptor

func WithStreamInterceptor(f StreamClientInterceptor) DialOption

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

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

func WithTransportCredentials

func WithTransportCredentials(creds credentials.TransportCredentials) DialOption

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

func WithUnaryInterceptor

func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption

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

func WithUserAgent

func WithUserAgent(s string) DialOption

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

type EmptyCallOption

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

type EmptyCallOption struct{}

type MethodConfig

MethodConfig defines the configuration recommended by the service providers for a particular method. This is EXPERIMENTAL and subject to change.

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 minumum 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
}

type MethodDesc

MethodDesc represents an RPC service's method specification.

type MethodDesc struct {
    MethodName string
    Handler    methodHandler
}

type MethodInfo

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

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
}

type Server

Server is a gRPC server to serve RPC requests.

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

func NewServer

func NewServer(opt ...ServerOption) *Server

NewServer creates a gRPC server which has no service registered and has not started 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) 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.

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

func (*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 always returns non-nil error.

func (*Server) ServeHTTP

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

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

type ServerOption

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

type ServerOption func(*options)

func Creds

func Creds(c credentials.TransportCredentials) ServerOption

Creds returns a ServerOption that sets credentials for server connections.

func CustomCodec

func CustomCodec(codec Codec) ServerOption

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

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

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

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

func KeepaliveEnforcementPolicy

func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption

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

func KeepaliveParams

func KeepaliveParams(kp keepalive.ServerParameters) ServerOption

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

func MaxConcurrentStreams

func MaxConcurrentStreams(n uint32) ServerOption

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

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

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

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

func RPCCompressor

func RPCCompressor(cp Compressor) ServerOption

RPCCompressor returns a ServerOption that sets a compressor for outbound messages.

func RPCDecompressor

func RPCDecompressor(dc Decompressor) ServerOption

RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages.

func StatsHandler

func StatsHandler(h stats.Handler) ServerOption

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

func StreamInterceptor

func StreamInterceptor(i StreamServerInterceptor) ServerOption

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

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

func 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 passes through interceptors.

type ServerStream

ServerStream defines the interface a server stream has to satisfy.

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
}

type ServiceConfig

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

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

type ServiceDesc

ServiceDesc represents an RPC service's specification.

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{}
}

type ServiceInfo

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

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

type Stream

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

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.
    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.
    RecvMsg(m interface{}) error
}

type StreamClientInterceptor

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.

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

type StreamDesc

StreamDesc represents a streaming RPC service's method specification.

type StreamDesc struct {
    StreamName string
    Handler    StreamHandler

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

type StreamHandler

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

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

type StreamServerInfo

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

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
}

type StreamServerInterceptor

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.

type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error

type Streamer

Streamer is called by StreamClientInterceptor to create a ClientStream.

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

type UnaryClientInterceptor

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.

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

type UnaryHandler

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

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

type UnaryInvoker

UnaryInvoker is called by UnaryClientInterceptor to complete RPCs.

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

type UnaryServerInfo

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

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
}

type UnaryServerInterceptor

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.

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

Subdirectories

Name Synopsis
..
benchmark Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks.
client
grpc_testing Package grpc_testing is a generated protocol buffer package.
server
stats
worker
codes Package codes defines the canonical error codes used by gRPC.
credentials 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.
oauth Package oauth implements gRPC credentials using OAuth.
examples
helloworld
greeter_client
greeter_server
helloworld Package helloworld is a generated protocol buffer package.
mock_helloworld
route_guide
client Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries to perform unary, client streaming, server streaming and full duplex RPCs.
mock_routeguide
routeguide Package routeguide is a generated protocol buffer package.
server Package main implements a simple gRPC server that demonstrates how to use gRPC-Go libraries to perform unary, client streaming, server streaming and full duplex RPCs.
grpclb
grpc_lb_v1 Package grpc_lb_v1 is a generated protocol buffer package.
grpclog Package grpclog defines logging for grpc.
glogger Package glogger defines glog-based logging for grpc.
health Package health provides some utility functions to health-check a server.
grpc_health_v1 Package grpc_health_v1 is a generated protocol buffer package.
interop
client
grpc_testing Package grpc_testing is a generated protocol buffer package.
http2
server
keepalive Package keepalive defines configurable parameters for point-to-point healthcheck.
metadata Package metadata define the structure of the metadata supported by gRPC library.
naming Package naming defines the naming API and related data structures for gRPC.
peer Package peer defines various peer information associated with RPCs and corresponding utils.
reflection Package reflection implements server reflection service.
grpc_reflection_v1alpha Package grpc_reflection_v1alpha is a generated protocol buffer package.
grpc_testing Package grpc_testing is a generated protocol buffer package.
stats Package stats is for collecting and reporting various network and RPC stats.
grpc_testing Package grpc_testing is a generated protocol buffer package.
status Package status implements errors returned by gRPC.
stress
client client starts an interop client to do stress test and a metrics server to report qps.
grpc_testing Package grpc_testing is a generated protocol buffer package.
metrics_client
tap Package tap defines the function handles which are executed on the transport layer of gRPC-Go and related information.
test
codec_perf Package codec_perf is a generated protocol buffer package.
grpc_testing Package grpc_testing is a generated protocol buffer package.
transport Package transport defines and implements message oriented communication channel to complete various transactions (e.g., an RPC).