Documentation ¶
Overview ¶
Package grpc implements an RPC system called gRPC.
See grpc.io for more information about gRPC.
Index ¶
- Constants
- Variables
- func Code(err error) codes.Codedeprecated
- func Error(w http.ResponseWriter, error string, code int)
- func ErrorDesc(err error) stringdeprecated
- func Errorf(c codes.Code, format string, a ...interface{}) errordeprecated
- func Handle(pattern string, handler http.Handler)
- func HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
- func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, ...) error
- func ListenAndServe(addr string, handler http.Handler) error
- func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) error
- func Method(ctx context.Context) (string, bool)
- func MethodFromServerStream(stream ServerStream) (string, bool)
- func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context
- func NotFound(w http.ResponseWriter, r *http.Request)
- func NotFoundHandler() http.Handler
- func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)
- func RedirectHandler(url string, code int) http.Handler
- func SendHeader(ctx context.Context, md metadata.MD) error
- func Serve(l net.Listener, handler http.Handler) error
- func ServeTLS(l net.Listener, handler http.Handler, certFile, keyFile string) error
- func SetHeader(ctx context.Context, md metadata.MD) error
- func SetTrailer(ctx context.Context, md metadata.MD) error
- func StripPrefix(prefix string, h http.Handler) http.Handler
- func TimeoutHandler(h http.Handler, dt time.Duration, msg string) http.Handler
- type Addressdeprecated
- type BackoffConfigdeprecated
- type Balancerdeprecated
- type BalancerConfigdeprecated
- type BalancerGetOptionsdeprecated
- type CallOption
- func CallContentSubtype(contentSubtype string) CallOption
- func CallCustomCodec(codec Codec) CallOptiondeprecated
- func FailFast(failFast bool) CallOptiondeprecated
- func ForceCodec(codec encoding.Codec) CallOption
- func Header(md *metadata.MD) CallOption
- func MaxCallRecvMsgSize(bytes int) CallOption
- func MaxCallSendMsgSize(bytes int) CallOption
- func MaxRetryRPCBufferSize(bytes int) CallOption
- func Peer(p *peer.Peer) CallOption
- func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption
- func Trailer(md *metadata.MD) CallOption
- func UseCompressor(name string) CallOption
- func WaitForReady(waitForReady bool) CallOption
- type ClientConn
- func (cc *ClientConn) Close() error
- func (cc *ClientConn) GetMethodConfig(method string) MethodConfig
- func (cc *ClientConn) GetState() connectivity.State
- func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, ...) error
- func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
- func (cc *ClientConn) ResetConnectBackoff()
- func (cc *ClientConn) Target() string
- func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool
- type ClientConnInterface
- type ClientStream
- type Codecdeprecated
- type Compressordeprecated
- type CompressorCallOption
- type ConnectParams
- type ContentSubtypeCallOption
- type CustomCodecCallOption
- type Decompressordeprecated
- func NewGZIPDecompressor() Decompressordeprecated
- type DialOption
- func FailOnNonTempDialError(f bool) DialOption
- func WithAuthority(a string) DialOption
- func WithBackoffConfig(b BackoffConfig) DialOptiondeprecated
- func WithBackoffMaxDelay(md time.Duration) DialOptiondeprecated
- func WithBalancer(b Balancer) DialOptiondeprecated
- func WithBalancerName(balancerName string) DialOptiondeprecated
- func WithBlock() DialOption
- func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption
- func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption
- func WithChannelzParentID(id int64) DialOption
- func WithCodec(c Codec) DialOptiondeprecated
- func WithCompressor(cp Compressor) DialOptiondeprecated
- func WithConnectParams(p ConnectParams) DialOption
- func WithContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption
- func WithCredentialsBundle(b credentials.Bundle) DialOption
- func WithDecompressor(dc Decompressor) DialOptiondeprecated
- func WithDefaultCallOptions(cos ...CallOption) DialOption
- func WithDefaultServiceConfig(s string) DialOption
- func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOptiondeprecated
- func WithDisableHealthCheck() DialOption
- func WithDisableRetry() DialOption
- func WithDisableServiceConfig() DialOption
- func WithInitialConnWindowSize(s int32) DialOption
- func WithInitialWindowSize(s int32) DialOption
- func WithInsecure() DialOption
- func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption
- func WithMaxHeaderListSize(s uint32) DialOption
- func WithMaxMsgSize(s int) DialOptiondeprecated
- func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption
- func WithReadBufferSize(s int) DialOption
- func WithResolvers(rs ...resolver.Builder) DialOption
- func WithServiceConfig(c <-chan ServiceConfig) DialOptiondeprecated
- func WithStatsHandler(h stats.Handler) DialOption
- func WithStreamInterceptor(f StreamClientInterceptor) DialOption
- func WithTimeout(d time.Duration) DialOptiondeprecated
- func WithTransportCredentials(creds credentials.TransportCredentials) DialOption
- func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption
- func WithUserAgent(s string) DialOption
- func WithWriteBufferSize(s int) DialOption
- type EmptyCallOption
- type EmptyDialOption
- type EmptyServerOption
- type FailFastCallOption
- type FlushAfterChunkWriter
- type ForceCodecCallOption
- type GServer
- type HandlerFunc
- type HeaderCallOption
- type MaxRecvMsgSizeCallOption
- type MaxRetryRPCBufferSizeCallOption
- type MaxSendMsgSizeCallOption
- type MethodConfigdeprecated
- type MethodDesc
- type MethodInfo
- type PeerCallOption
- type PerRPCCredsCallOption
- type PreparedMsg
- type ServeMux
- func (mux *ServeMux) Handle(pattern string, handler http.Handler)
- func (mux *ServeMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
- func (mux *ServeMux) Handler(r *http.Request) (h http.Handler, pattern string)
- func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type Server
- func (srv *Server) Close() error
- func (s *Server) GetServiceInfo() map[string]ServiceInfo
- func (s *Server) GracefulStop()
- func (srv *Server) ListenAndServe() error
- func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
- func (srv *Server) RegisterOnShutdown(f func())
- func (s *Server) RegisterService(sd *ServiceDesc, ss interface{})
- func (s *Server) Serve(lis net.Listener) error
- func (srv *Server) Serve2(l net.Listener) error
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error
- func (srv *Server) SetKeepAlivesEnabled(v bool)
- func (s *Server) SetMux(mux http.Handler)
- func (srv *Server) Shutdown(ctx context.Context) error
- func (s *Server) Stop()
- type ServerOption
- func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption
- func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption
- func ConnectionTimeout(d time.Duration) ServerOption
- func Creds(c credentials.TransportCredentials) ServerOption
- func CustomCodec(codec Codec) ServerOption
- func HeaderTableSize(s uint32) 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 MaxHeaderListSize(s uint32) ServerOption
- func MaxMsgSize(m int) ServerOptiondeprecated
- func MaxRecvMsgSize(m int) ServerOption
- func MaxSendMsgSize(m int) ServerOption
- func RPCCompressor(cp Compressor) ServerOptiondeprecated
- func RPCDecompressor(dc Decompressor) ServerOptiondeprecated
- func ReadBufferSize(s int) ServerOption
- func StatsHandler(h stats.Handler) ServerOption
- func StreamInterceptor(i StreamServerInterceptor) ServerOption
- func UnaryInterceptor(i UnaryServerInterceptor) ServerOption
- func UnknownServiceHandler(streamHandler StreamHandler) ServerOption
- func WriteBufferSize(s int) ServerOption
- type ServerStream
- type ServerTransportStream
- type ServiceConfigdeprecated
- type ServiceDesc
- type ServiceInfo
- type Streamdeprecated
- type StreamClientInterceptor
- type StreamDesc
- type StreamHandler
- type StreamServerInfo
- type StreamServerInterceptor
- type Streamer
- type TrailerCallOption
- type UnaryClientInterceptor
- type UnaryHandler
- type UnaryInvoker
- type UnaryServerInfo
- type UnaryServerInterceptor
Constants ¶
const ( SupportPackageIsVersion3 = true SupportPackageIsVersion4 = true SupportPackageIsVersion5 = true SupportPackageIsVersion6 = 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 6.
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.
const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
DefaultMaxHeaderBytes is the maximum permitted size of the headers in an HTTP request. This can be overridden by setting Server.MaxHeaderBytes.
const PickFirstBalancerName = "pick_first"
PickFirstBalancerName is the name of the pick_first balancer.
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
TimeFormat is the time format to use when generating times in HTTP headers. It is like time.RFC1123 but hard-codes GMT as the time zone. The time being formatted must be in UTC for Format to generate the correct format.
For parsing this time format, see ParseTime.
const Version = "1.28.1"
Version is the current grpc version.
Variables ¶
var DefaultBackoffConfig = BackoffConfig{ MaxDelay: 120 * time.Second, }
DefaultBackoffConfig uses values specified for backoff in https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
Deprecated: use ConnectParams instead. Will be supported throughout 1.x.
var DefaultServeMux = &defaultServeMux
DefaultServeMux is the default ServeMux used by Serve.
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.
ErrBodyReadAfterClose is returned when reading a Request or Response Body after the body has been closed. This typically happens when the body is read after an HTTP Handler calls WriteHeader or Write on its ResponseWriter.
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 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.
ErrHandlerTimeout is returned on http.ResponseWriter Write calls in handlers which have timed out.
ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe, and ListenAndServeTLS methods after a call to Shutdown or Close.
ErrServerStopped indicates that the operation is now illegal because of the server being stopped.
Functions ¶
func Error ¶
func Error(w http.ResponseWriter, error string, code int)
Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.
func Handle ¶
Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.
func HandleFunc ¶
func HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.
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. This is typically called by generated code.
DEPRECATED: Use ClientConn.Invoke instead.
func ListenAndServe ¶
ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.
The handler is typically nil, in which case the DefaultServeMux is used.
ListenAndServe always returns a non-nil error.
func ListenAndServeTLS ¶
ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.
func Method ¶
Method returns the method string for the server context. The returned string is in the format of "/service/method".
func 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".
func NewContextWithServerTransportStream ¶
func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context
NewContextWithServerTransportStream creates a new context from ctx and attaches stream to it.
This API is EXPERIMENTAL.
func NotFound ¶
func NotFound(w http.ResponseWriter, r *http.Request)
NotFound replies to the request with an HTTP 404 not found error.
func NotFoundHandler ¶
NotFoundHandler returns a simple request handler that replies to each request with a “404 page not found” reply.
func Redirect ¶
Redirect replies to the request with a redirect to url, which may be a path relative to the request path.
The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.
If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body. Setting the Content-Type header to any value, including nil, disables that behavior.
func RedirectHandler ¶
RedirectHandler returns a request handler that redirects each request it receives to the given url using the given status code.
The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.
func SendHeader ¶
SendHeader sends header metadata. It may be called at most once. The provided md and headers set by SetHeader() will be sent.
func Serve ¶
Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.
The handler is typically nil, in which case the DefaultServeMux is used.
HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with "h2" in the TLS Config.NextProtos.
Serve always returns a non-nil error.
func ServeTLS ¶
ServeTLS accepts incoming HTTPS connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.
The handler is typically nil, in which case the DefaultServeMux is used.
Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.
ServeTLS always returns a non-nil error.
func SetHeader ¶
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 ¶
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.
func StripPrefix ¶
StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.
func TimeoutHandler ¶
TimeoutHandler returns a http.Handler that runs h with the given time limit.
The new http.Handler calls h.ServeHTTP to handle each request, but if a call runs for longer than its time limit, the handler responds with a 503 Service Unavailable error and the given message in its body. (If msg is empty, a suitable default message will be sent.) After such a timeout, writes by h to its http.ResponseWriter will return ErrHandlerTimeout.
TimeoutHandler supports the Pusher interface but does not support the Hijacker or Flusher interfaces.
Types ¶
type Address
deprecated
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.
Deprecated: please use package balancer.
type Balancer
deprecated
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.
Deprecated: please use package balancer. May be removed in a future 1.x release.
func RoundRobin
deprecated
RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch the name resolution updates and updates the addresses available correspondingly.
Deprecated: please use package balancer/roundrobin. May be removed in a future 1.x release.
type BalancerConfig
deprecated
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.
Deprecated: please use package balancer. May be removed in a future 1.x release.
type BalancerGetOptions
deprecated
type BalancerGetOptions struct { // BlockingWait specifies whether Get should block when there is no // connected address. BlockingWait bool }
BalancerGetOptions configures a Get call.
Deprecated: please use package balancer. May be removed in a future 1.x release.
type 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.
func CallContentSubtype ¶
func CallContentSubtype(contentSubtype string) CallOption
CallContentSubtype returns a CallOption that will set the content-subtype for a call. For example, if content-subtype is "json", the Content-Type over the wire will be "application/grpc+json". The content-subtype is converted to lowercase before being included in Content-Type. See Content-Type on https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for more details.
If ForceCodec is not also used, the content-subtype will be used to look up the Codec to use in the registry controlled by RegisterCodec. See the documentation on RegisterCodec for details on registration. The lookup of content-subtype is case-insensitive. If no such Codec is found, the call will result in an error with code codes.Internal.
If ForceCodec is also used, that Codec will be used for all request and response messages, with the content-subtype set to the given contentSubtype here for requests.
func CallCustomCodec
deprecated
func CallCustomCodec(codec Codec) CallOption
CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of an encoding.Codec.
Deprecated: use ForceCodec instead.
func FailFast
deprecated
func FailFast(failFast bool) CallOption
FailFast is the opposite of WaitForReady.
Deprecated: use WaitForReady.
func ForceCodec ¶
func ForceCodec(codec encoding.Codec) CallOption
ForceCodec 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.
This is an EXPERIMENTAL API.
func Header ¶
func Header(md *metadata.MD) CallOption
Header returns a CallOptions that retrieves the header metadata for a unary RPC.
func MaxCallRecvMsgSize ¶
func MaxCallRecvMsgSize(bytes int) CallOption
MaxCallRecvMsgSize returns a CallOption which sets the maximum message size in bytes the client can receive.
func MaxCallSendMsgSize ¶
func MaxCallSendMsgSize(bytes int) CallOption
MaxCallSendMsgSize returns a CallOption which sets the maximum message size in bytes the client can send.
func MaxRetryRPCBufferSize ¶
func MaxRetryRPCBufferSize(bytes int) CallOption
MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory used for buffering this RPC's requests for retry purposes.
This API is EXPERIMENTAL.
func Peer ¶
func Peer(p *peer.Peer) CallOption
Peer returns a CallOption that retrieves peer information for a unary RPC. The peer field will be populated *after* the RPC completes.
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.
func 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.
func WaitForReady ¶
func WaitForReady(waitForReady bool) CallOption
WaitForReady configures the action to take when an RPC is attempted on broken connections or unreachable servers. If waitForReady is false, 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 don't "wait for ready".
type ClientConn ¶
type ClientConn struct {
// contains filtered or unexported fields
}
ClientConn represents a virtual connection to a conceptual endpoint, to perform RPCs.
A ClientConn is free to have zero or more actual connections to the endpoint based on configuration, load, etc. It is also free to determine which actual endpoints to use and may change it every RPC, permitting client-side load balancing.
A ClientConn encapsulates a range of functionality including name resolution, TCP connection establishment (with retries and backoff) and TLS handshakes. It also handles errors on established connections by re-resolving the name and reconnecting.
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. By default, it's a non-blocking dial (the function won't wait for connections to be established, and connecting happens in the background). To make it a blocking dial, use WithBlock() dial option.
In the non-blocking case, the ctx does not act against the connection. It only controls the setup steps.
In the blocking case, 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.
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 service, we return it. Otherwise, we return an empty MethodConfig.
func (*ClientConn) GetState ¶
func (cc *ClientConn) GetState() connectivity.State
GetState returns the connectivity.State of ClientConn. This is an EXPERIMENTAL API.
func (*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.
func (*ClientConn) NewStream ¶
func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
NewStream creates a new Stream for the client side. This is typically called by generated code. ctx is used for the lifetime of the stream.
To ensure resources are not leaked due to the stream returned, one of the following actions must be performed:
- Call Close on the ClientConn.
- Cancel the context provided.
- Call RecvMsg until a non-nil error is returned. A protobuf-generated client-streaming RPC, for instance, might use the helper function CloseAndRecv (note that CloseSend does not Recv, therefore is not guaranteed to release all resources).
- Receive a non-nil, non-io.EOF error from Header or SendMsg.
If none of the above happen, a goroutine and a context will be leaked, and grpc will not call the optionally-configured stats handler with a stats.End message.
func (*ClientConn) ResetConnectBackoff ¶
func (cc *ClientConn) ResetConnectBackoff()
ResetConnectBackoff wakes up all subchannels in transient failure and causes them to attempt another connection immediately. It also resets the backoff times used for subsequent attempts regardless of the current state.
In general, this function should not be used. Typical service or network outages result in a reasonable client reconnection strategy by default. However, if a previously unavailable network becomes available, this may be used to trigger an immediate reconnect.
This API is EXPERIMENTAL.
func (*ClientConn) Target ¶
func (cc *ClientConn) Target() string
Target returns the target string of the ClientConn. This is an EXPERIMENTAL API.
func (*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.
type ClientConnInterface ¶
type ClientConnInterface interface { // Invoke performs a unary RPC and returns after the response is received // into reply. Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...CallOption) error // NewStream begins a streaming RPC. NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) }
ClientConnInterface defines the functions clients need to perform unary and streaming RPCs. It is implemented by *ClientConn, and is only intended to be referenced by generated code.
type 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. It is also not safe to call CloseSend // concurrently with SendMsg. CloseSend() error // Context returns the context for this stream. // // It should not be called until after Header or RecvMsg has returned. Once // called, subsequent client-side retries are disabled. Context() context.Context // SendMsg is generally called by generated code. On error, SendMsg aborts // the stream. If the error was generated by the client, the status is // returned directly; otherwise, io.EOF is returned and the status of // the stream may be discovered using RecvMsg. // // SendMsg blocks until: // - There is sufficient flow control to schedule m with the transport, or // - The stream is done, or // - The stream breaks. // // SendMsg does not wait until the message is received by the server. An // untimely stream closure may result in lost messages. To ensure delivery, // users should ensure the RPC completed successfully using RecvMsg. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not safe // to call SendMsg on the same stream in different goroutines. It is also // not safe to call CloseSend concurrently with SendMsg. SendMsg(m interface{}) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the stream completes successfully. On // any other error, the stream is aborted and the error contains the RPC // status. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not // safe to call RecvMsg on the same stream in different goroutines. RecvMsg(m interface{}) error }
ClientStream defines the client-side behavior of a streaming RPC.
All errors returned from ClientStream methods are compatible with the status package.
func NewClientStream ¶
func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)
NewClientStream is a wrapper for ClientConn.NewStream.
type Codec
deprecated
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.
type Compressor
deprecated
type Compressor interface { // Do compresses p into w. Do(w io.Writer, p []byte) error // Type returns the compression algorithm the Compressor uses. Type() string }
Compressor defines the interface gRPC uses to compress a message.
Deprecated: use package encoding.
func NewGZIPCompressor
deprecated
func NewGZIPCompressor() Compressor
NewGZIPCompressor creates a Compressor based on GZIP.
Deprecated: use package encoding/gzip.
func NewGZIPCompressorWithLevel
deprecated
func NewGZIPCompressorWithLevel(level int) (Compressor, error)
NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead of assuming DefaultCompression.
The error returned will be nil if the level is valid.
Deprecated: use package encoding/gzip.
type CompressorCallOption ¶
type CompressorCallOption struct {
CompressorType string
}
CompressorCallOption is a CallOption that indicates the compressor to use. This is an EXPERIMENTAL API.
type ConnectParams ¶
type ConnectParams struct { // Backoff specifies the configuration options for connection backoff. Backoff backoff.Config // MinConnectTimeout is the minimum amount of time we are willing to give a // connection to complete. MinConnectTimeout time.Duration }
ConnectParams defines the parameters for connecting and retrying. Users are encouraged to use this instead of the BackoffConfig type defined above. See here for more details: https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
This API is EXPERIMENTAL.
type ContentSubtypeCallOption ¶
type ContentSubtypeCallOption struct {
ContentSubtype string
}
ContentSubtypeCallOption is a CallOption that indicates the content-subtype used for marshaling messages. This is an EXPERIMENTAL API.
type CustomCodecCallOption ¶
type CustomCodecCallOption struct {
Codec Codec
}
CustomCodecCallOption is a CallOption that indicates the codec used for marshaling messages.
This is an EXPERIMENTAL API.
type Decompressor
deprecated
type Decompressor interface { // Do reads the data from r and uncompress them. Do(r io.Reader) ([]byte, error) // Type returns the compression algorithm the Decompressor uses. Type() string }
Decompressor defines the interface gRPC uses to decompress a message.
Deprecated: use package encoding.
func NewGZIPDecompressor
deprecated
func NewGZIPDecompressor() Decompressor
NewGZIPDecompressor creates a Decompressor based on GZIP.
Deprecated: use package encoding/gzip.
type DialOption ¶
type DialOption interface {
// contains filtered or unexported methods
}
DialOption configures how we set up the connection.
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.
FailOnNonTempDialError only affects the initial dial, and does not do anything useful unless you are also using WithBlock().
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
deprecated
func WithBackoffConfig(b BackoffConfig) DialOption
WithBackoffConfig configures the dialer to use the provided backoff parameters after connection failures.
Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.
func WithBackoffMaxDelay
deprecated
func WithBackoffMaxDelay(md time.Duration) DialOption
WithBackoffMaxDelay configures the dialer to use the provided maximum delay when backing off after failed connection attempts.
Deprecated: use WithConnectParams instead. Will be supported throughout 1.x.
func WithBalancer
deprecated
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. Will be removed in a future 1.x release.
func WithBalancerName
deprecated
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.
Deprecated: use WithDefaultServiceConfig and WithDisableServiceConfig instead. Will be removed in a future 1.x release.
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 WithChainStreamInterceptor ¶
func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption
WithChainStreamInterceptor returns a DialOption that specifies the chained interceptor for unary RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All interceptors added by this method will be chained, and the interceptor defined by WithStreamInterceptor will always be prepended to the chain.
func WithChainUnaryInterceptor ¶
func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption
WithChainUnaryInterceptor returns a DialOption that specifies the chained interceptor for unary RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All interceptors added by this method will be chained, and the interceptor defined by WithUnaryInterceptor will always be prepended to the chain.
func WithChannelzParentID ¶
func WithChannelzParentID(id int64) DialOption
WithChannelzParentID returns a DialOption that specifies the channelz ID of current ClientConn's parent. This function is used in nested channel creation (e.g. grpclb dial).
This API is EXPERIMENTAL.
func WithCodec
deprecated
func WithCodec(c Codec) DialOption
WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.
Deprecated: use WithDefaultCallOptions(ForceCodec(_)) instead. Will be supported throughout 1.x.
func WithCompressor
deprecated
func WithCompressor(cp Compressor) DialOption
WithCompressor returns a DialOption which sets a Compressor to use for message compression. It has lower priority than the compressor set by the UseCompressor CallOption.
Deprecated: use UseCompressor instead. Will be supported throughout 1.x.
func WithConnectParams ¶
func WithConnectParams(p ConnectParams) DialOption
WithConnectParams configures the dialer to use the provided ConnectParams.
The backoff configuration specified as part of the ConnectParams overrides all defaults specified in https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Consider using the backoff.DefaultConfig as a base, in cases where you want to override only a subset of the backoff configuration.
This API is EXPERIMENTAL.
func WithContextDialer ¶
WithContextDialer returns a DialOption that sets a dialer to create connections. If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's Temporary() method to decide if it should try to reconnect to the network address.
func WithCredentialsBundle ¶
func WithCredentialsBundle(b credentials.Bundle) DialOption
WithCredentialsBundle returns a DialOption to set a credentials bundle for the ClientConn.WithCreds. This should not be used together with WithTransportCredentials.
This API is experimental.
func WithDecompressor
deprecated
func WithDecompressor(dc Decompressor) DialOption
WithDecompressor returns a DialOption which sets a Decompressor to use for incoming message decompression. If incoming response messages are encoded using the decompressor's Type(), it will be used. Otherwise, the message encoding will be used to look up the compressor registered via encoding.RegisterCompressor, which will then be used to decompress the message. If no compressor is registered for the encoding, an Unimplemented status error will be returned.
Deprecated: use encoding.RegisterCompressor instead. Will be supported throughout 1.x.
func WithDefaultCallOptions ¶
func WithDefaultCallOptions(cos ...CallOption) DialOption
WithDefaultCallOptions returns a DialOption which sets the default CallOptions for calls over the connection.
func WithDefaultServiceConfig ¶
func WithDefaultServiceConfig(s string) DialOption
WithDefaultServiceConfig returns a DialOption that configures the default service config, which will be used in cases where:
- WithDisableServiceConfig is also used.
- Resolver does not return a service config or if the resolver returns an invalid service config.
This API is EXPERIMENTAL.
func WithDialer
deprecated
WithDialer returns a DialOption that specifies a function to use for dialing network addresses. If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's Temporary() method to decide if it should try to reconnect to the network address.
Deprecated: use WithContextDialer instead. Will be supported throughout 1.x.
func WithDisableHealthCheck ¶
func WithDisableHealthCheck() DialOption
WithDisableHealthCheck disables the LB channel health checking for all SubConns of this ClientConn.
This API is EXPERIMENTAL.
func WithDisableRetry ¶
func WithDisableRetry() DialOption
WithDisableRetry returns a DialOption that disables retries, even if the service config enables them. This does not impact transparent retries, which will happen automatically if no data is written to the wire or if the RPC is unprocessed by the remote server.
Retry support is currently disabled by default, but will be enabled by default in the future. Until then, it may be enabled by setting the environment variable "GRPC_GO_RETRY" to "on".
This API is EXPERIMENTAL.
func WithDisableServiceConfig ¶
func WithDisableServiceConfig() DialOption
WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any service config provided by the resolver and provides a hint to the resolver to not fetch service configs.
Note that this dial option only disables service config from resolver. If default service config is provided, gRPC will use the default service config.
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 parameters for the client transport.
func WithMaxHeaderListSize ¶
func WithMaxHeaderListSize(s uint32) DialOption
WithMaxHeaderListSize returns a DialOption that specifies the maximum (uncompressed) size of header list that the client is prepared to accept.
func WithMaxMsgSize
deprecated
func WithMaxMsgSize(s int) DialOption
WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive.
Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. Will be supported throughout 1.x.
func WithPerRPCCredentials ¶
func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption
WithPerRPCCredentials returns a DialOption which sets credentials and places auth state on each outbound RPC.
func WithReadBufferSize ¶
func WithReadBufferSize(s int) DialOption
WithReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most for each read syscall.
The default value for this buffer is 32KB. Zero will disable read buffer for a connection so data framer can access the underlying conn directly.
func WithResolvers ¶
func WithResolvers(rs ...resolver.Builder) DialOption
WithResolvers allows a list of resolver implementations to be registered locally with the ClientConn without needing to be globally registered via resolver.Register. They will be matched against the scheme used for the current Dial only, and will take precedence over the global registry.
This API is EXPERIMENTAL.
func WithServiceConfig
deprecated
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 or via WithDefaultServiceConfig, as specified at https://github.com/grpc/grpc/blob/master/doc/service_config.md. Will be removed in a future 1.x release.
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
deprecated
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 instead of Dial and context.WithTimeout instead. Will be supported throughout 1.x.
func WithTransportCredentials ¶
func WithTransportCredentials(creds credentials.TransportCredentials) DialOption
WithTransportCredentials returns a DialOption which configures a connection level security credentials (e.g., TLS/SSL). This should not be used together with WithCredentialsBundle.
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.
func WithWriteBufferSize ¶
func WithWriteBufferSize(s int) DialOption
WithWriteBufferSize determines how much data can be batched before doing a write on the wire. The corresponding memory allocation for this buffer will be twice the size to keep syscalls low. The default value for this buffer is 32KB.
Zero will disable the write buffer such that each write will be on underlying connection. Note: A Send call may not directly translate to a write.
type 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.
type EmptyDialOption ¶
type EmptyDialOption struct{}
EmptyDialOption does not alter the dial configuration. It can be embedded in another structure to build custom dial options.
This API is EXPERIMENTAL.
type EmptyServerOption ¶
type EmptyServerOption struct{}
EmptyServerOption does not alter the server configuration. It can be embedded in another structure to build custom server options.
This API is EXPERIMENTAL.
type FailFastCallOption ¶
type FailFastCallOption struct {
FailFast bool
}
FailFastCallOption is a CallOption for indicating whether an RPC should fail fast or not. This is an EXPERIMENTAL API.
type FlushAfterChunkWriter ¶
FlushAfterChunkWriter signals from the caller of NewChunkedWriter that each chunk should be followed by a flush. It is used by the http.Transport code to keep the buffering behavior for headers and trailers, but flush out chunks aggressively in the middle for request bodies which may be generated slowly. See Issue 6574.
type ForceCodecCallOption ¶
ForceCodecCallOption is a CallOption that indicates the codec used for marshaling messages.
This is an EXPERIMENTAL API.
type GServer ¶
type GServer struct { BaseContext func(net.Listener) context.Context ReadTimeout int // contains filtered or unexported fields }
Server is a gRPC server to serve RPC requests.
type HandlerFunc ¶
type HandlerFunc func(http.ResponseWriter, *http.Request)
The http.HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, http.HandlerFunc(f) is a http.Handler that calls f.
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP calls f(w, r).
type HeaderCallOption ¶
HeaderCallOption is a CallOption for collecting response header metadata. The metadata field will be populated *after* the RPC completes. This is an EXPERIMENTAL API.
type MaxRecvMsgSizeCallOption ¶
type MaxRecvMsgSizeCallOption struct {
MaxRecvMsgSize int
}
MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message size in bytes the client can receive. This is an EXPERIMENTAL API.
type MaxRetryRPCBufferSizeCallOption ¶
type MaxRetryRPCBufferSizeCallOption struct {
MaxRetryRPCBufferSize int
}
MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of memory to be used for caching this RPC for retry purposes. This is an EXPERIMENTAL API.
type MaxSendMsgSizeCallOption ¶
type MaxSendMsgSizeCallOption struct {
MaxSendMsgSize int
}
MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message size in bytes the client can send. This is an EXPERIMENTAL API.
type MethodConfig
deprecated
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 // contains filtered or unexported fields }
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
type MethodDesc ¶
type MethodDesc struct { MethodName string Handler methodHandler }
MethodDesc represents an RPC service's method specification.
type 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.
type PeerCallOption ¶
PeerCallOption is a CallOption for collecting the identity of the remote peer. The peer field will be populated *after* the RPC completes. This is an EXPERIMENTAL API.
type PerRPCCredsCallOption ¶
type PerRPCCredsCallOption struct {
Creds credentials.PerRPCCredentials
}
PerRPCCredsCallOption is a CallOption that indicates the per-RPC credentials to use for the call. This is an EXPERIMENTAL API.
type PreparedMsg ¶
type PreparedMsg struct {
// contains filtered or unexported fields
}
PreparedMsg is responsible for creating a Marshalled and Compressed object.
This API is EXPERIMENTAL.
func (*PreparedMsg) Encode ¶
func (p *PreparedMsg) Encode(s Stream, msg interface{}) error
Encode marshalls and compresses the message using the codec and compressor for the stream.
type ServeMux ¶
type ServeMux struct {
// contains filtered or unexported fields
}
ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.
Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.
Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".
If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash). This behavior can be overridden with a separate registration for the path without the trailing slash. For example, registering "/images/" causes ServeMux to redirect a request for "/images" to "/images/", unless "/images" has been registered separately.
Patterns may optionally begin with a host name, restricting matches to URLs on that host only. Host-specific patterns take precedence over general patterns, so that a handler might register for the two patterns "/codesearch" and "codesearch.google.com/" without also taking over requests for "http://www.google.com/".
ServeMux also takes care of sanitizing the URL request path and the Host header, stripping the port number and redirecting any request containing . or .. elements or repeated slashes to an equivalent, cleaner URL.
func (*ServeMux) Handle ¶
Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.
func (*ServeMux) HandleFunc ¶
HandleFunc registers the handler function for the given pattern.
func (*ServeMux) Handler ¶
http.Handler returns the handler to use for the given request, consulting r.Method, r.Host, and r.URL.Path. It always returns a non-nil handler. If the path is not in its canonical form, the handler will be an internally-generated handler that redirects to the canonical path. If the host contains a port, it is ignored when matching handlers.
The path and host are used unchanged for CONNECT requests.
http.Handler also returns the registered pattern that matches the request or, in the case of internally-generated redirects, the pattern that will match after following the redirect.
If there is no registered handler that applies to the request, http.Handler returns a “page not found” handler and an empty pattern.
type Server ¶
type Server struct { GServer // Addr optionally specifies the TCP address for the server to listen on, // in the form "host:port". If empty, ":http" (port 80) is used. // The service names are defined in RFC 6335 and assigned by IANA. // See net.Dial for details of the address format. Addr string Handler http.Handler // handler to invoke, http.DefaultServeMux if nil // TLSConfig optionally provides a TLS configuration for use // by ServeTLS and ListenAndServeTLS. Note that this value is // cloned by ServeTLS and ListenAndServeTLS, so it's not // possible to modify the configuration with methods like // tls.Config.SetSessionTicketKeys. To use // SetSessionTicketKeys, use Server.Serve with a TLS Listener // instead. TLSConfig *tls.Config // ReadTimeout is the maximum duration for reading the entire // request, including the body. // // Because ReadTimeout does not let http.Handlers make per-request // decisions on each request body's acceptable deadline or // upload rate, most users will prefer to use // ReadHeaderTimeout. It is valid to use them both. ReadTimeout time.Duration // ReadHeaderTimeout is the amount of time allowed to read // request headers. The connection's read deadline is reset // after reading the headers and the http.Handler can decide what // is considered too slow for the body. If ReadHeaderTimeout // is zero, the value of ReadTimeout is used. If both are // zero, there is no timeout. ReadHeaderTimeout time.Duration // WriteTimeout is the maximum duration before timing out // writes of the response. It is reset whenever a new // request's header is read. Like ReadTimeout, it does not // let http.Handlers make decisions on a per-request basis. WriteTimeout time.Duration // IdleTimeout is the maximum amount of time to wait for the // next request when keep-alives are enabled. If IdleTimeout // is zero, the value of ReadTimeout is used. If both are // zero, there is no timeout. IdleTimeout time.Duration // MaxHeaderBytes controls the maximum number of bytes the // server will read parsing the request header's keys and // values, including the request line. It does not limit the // size of the request body. // If zero, DefaultMaxHeaderBytes is used. MaxHeaderBytes int // TLSNextProto optionally specifies a function to take over // ownership of the provided TLS connection when an ALPN // protocol upgrade has occurred. The map key is the protocol // name negotiated. The http.Handler argument should be used to // handle HTTP requests and will initialize the Request's TLS // and RemoteAddr if not already set. The connection is // automatically closed when the function returns. // If TLSNextProto is not nil, HTTP/2 support is not enabled // automatically. TLSNextProto map[string]func(*Server, *tls.Conn, http.Handler) // ConnState specifies an optional callback function that is // called when a client connection changes state. See the // ConnState type and associated constants for details. ConnState func(net.Conn, http.ConnState) // ErrorLog specifies an optional logger for errors accepting // connections, unexpected behavior from handlers, and // underlying FileSystem errors. // If nil, logging is done via the log package's standard logger. ErrorLog *log.Logger // BaseContext optionally specifies a function that returns // the base context for incoming requests on this server. // The provided Listener is the specific Listener that's // about to start accepting requests. // If BaseContext is nil, the default is context.Background(). // If non-nil, it must return a non-nil context. BaseContext func(net.Listener) context.Context // ConnContext optionally specifies a function that modifies // the context used for a new connection c. The provided ctx // is derived from the base context and has a ServerContextKey // value. ConnContext func(ctx context.Context, c net.Conn) context.Context // contains filtered or unexported fields }
A Server defines parameters for running an HTTP server. The zero value for Server is a valid configuration.
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) Close ¶
Close immediately closes all active net.Listeners and any connections in state StateNew, StateActive, or StateIdle. For a graceful shutdown, use Shutdown.
Close does not attempt to close (and does not even know about) any hijacked connections, such as WebSockets.
Close returns any error returned from closing the Server's underlying Listener(s).
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) ListenAndServe ¶
ListenAndServe listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.
If srv.Addr is blank, ":http" is used.
ListenAndServe always returns a non-nil error. After Shutdown or Close, the returned error is ErrServerClosed.
func (*Server) ListenAndServeTLS ¶
ListenAndServeTLS listens on the TCP network address srv.Addr and then calls ServeTLS to handle requests on incoming TLS connections. Accepted connections are configured to enable TCP keep-alives.
Filenames containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.
If srv.Addr is blank, ":https" is used.
ListenAndServeTLS always returns a non-nil error. After Shutdown or Close, the returned error is ErrServerClosed.
func (*Server) RegisterOnShutdown ¶
func (srv *Server) RegisterOnShutdown(f func())
RegisterOnShutdown registers a function to call on Shutdown. This can be used to gracefully shutdown connections that have undergone ALPN protocol upgrade or that have been hijacked. This function should start protocol-specific graceful shutdown, but should not wait for shutdown to complete.
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 ¶
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.
func (*Server) Serve2 ¶
Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them.
HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with "h2" in the TLS Config.NextProtos.
Serve always returns a non-nil error and closes l. After Shutdown or Close, the returned error is ErrServerClosed.
func (*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.
func (*Server) ServeTLS ¶
ServeTLS accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines perform TLS setup and then read requests, calling srv.Handler to reply to them.
Files containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.
ServeTLS always returns a non-nil error. After Shutdown or Close, the returned error is ErrServerClosed.
func (*Server) SetKeepAlivesEnabled ¶
SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default, keep-alives are always enabled. Only very resource-constrained environments or servers in the process of shutting down should disable them.
func (*Server) Shutdown ¶
Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).
When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed. Make sure the program doesn't exit and waits instead for Shutdown to return.
Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close, if desired. See RegisterOnShutdown for a way to register shutdown notification functions.
Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed.
type ServerOption ¶
type ServerOption interface {
// contains filtered or unexported methods
}
A ServerOption sets options such as credentials, codec and keepalive parameters, etc.
func ChainStreamInterceptor ¶
func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption
ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor for stream RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All stream interceptors added by this method will be chained.
func ChainUnaryInterceptor ¶
func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption
ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor for unary RPCs. The first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call. All unary interceptors added by this method will be chained.
func 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.
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.
This will override any lookups by content-subtype for Codecs registered with RegisterCodec.
func HeaderTableSize ¶
func HeaderTableSize(s uint32) ServerOption
HeaderTableSize returns a ServerOption that sets the size of dynamic header table for stream.
This API is EXPERIMENTAL.
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 MaxHeaderListSize ¶
func MaxHeaderListSize(s uint32) ServerOption
MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size of header list that the server is prepared to accept.
func MaxMsgSize
deprecated
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 `math.MaxInt32`.
func RPCCompressor
deprecated
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.
func RPCDecompressor
deprecated
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.
func ReadBufferSize ¶
func ReadBufferSize(s int) ServerOption
ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most for one read syscall. The default value for this buffer is 32KB. Zero will disable read buffer for a connection so data framer can access the underlying conn directly.
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 and stream interceptor (if set) have full access to the ServerStream, including its Context.
func WriteBufferSize ¶
func WriteBufferSize(s int) ServerOption
WriteBufferSize determines how much data can be batched before doing a write on the wire. The corresponding memory allocation for this buffer will be twice the size to keep syscalls low. The default value for this buffer is 32KB. Zero will disable the write buffer such that each write will be on underlying connection. Note: A Send call may not directly translate to a write.
type ServerStream ¶
type ServerStream interface { // SetHeader sets the header metadata. It may be called multiple times. // When call multiple times, all the provided metadata will be merged. // All the metadata will be sent out when one of the following happens: // - ServerStream.SendHeader() is called; // - The first response is sent out; // - An RPC status is sent out (error or success). SetHeader(metadata.MD) error // SendHeader sends the header metadata. // The provided md and headers set by SetHeader() will be sent. // It fails if called multiple times. SendHeader(metadata.MD) error // SetTrailer sets the trailer metadata which will be sent with the RPC status. // When called more than once, all the provided metadata will be merged. SetTrailer(metadata.MD) // Context returns the context for this stream. Context() context.Context // SendMsg sends a message. On error, SendMsg aborts the stream and the // error is returned directly. // // SendMsg blocks until: // - There is sufficient flow control to schedule m with the transport, or // - The stream is done, or // - The stream breaks. // // SendMsg does not wait until the message is received by the client. An // untimely stream closure may result in lost messages. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not safe // to call SendMsg on the same stream in different goroutines. SendMsg(m interface{}) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the client has performed a CloseSend. On // any non-EOF error, the stream is aborted and the error contains the // RPC status. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not // safe to call RecvMsg on the same stream in different goroutines. RecvMsg(m interface{}) error }
ServerStream defines the server-side behavior of a streaming RPC.
All errors returned from ServerStream methods are compatible with the status package.
type ServerTransportStream ¶
type ServerTransportStream interface { Method() string SetHeader(md metadata.MD) error SendHeader(md metadata.MD) error SetTrailer(md metadata.MD) error }
ServerTransportStream is a minimal interface that a transport stream must implement. This can be used to mock an actual transport stream for tests of handler code that use, for example, grpc.SetHeader (which requires some stream to be in context).
See also NewContextWithServerTransportStream.
This API is EXPERIMENTAL.
func ServerTransportStreamFromContext ¶
func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream
ServerTransportStreamFromContext returns the ServerTransportStream saved in ctx. Returns nil if the given context has no stream associated with it (which implies it is not an RPC invocation context).
This API is EXPERIMENTAL.
type ServiceConfig
deprecated
type ServiceConfig struct { serviceconfig.Config // LB is the load balancer the service providers recommends. The balancer // specified via grpc.WithBalancer will override this. This is deprecated; // lbConfigs is preferred. If lbConfig and LB are both present, lbConfig // will be used. 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 // contains filtered or unexported fields }
ServiceConfig is provided by the service provider and contains parameters for how clients that connect to the service should behave.
Deprecated: Users should not use this struct. Service config should be received through name resolver, as specified here https://github.com/grpc/grpc/blob/master/doc/service_config.md
type 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.
type 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.
type Stream
deprecated
type Stream interface { // Deprecated: See ClientStream and ServerStream documentation instead. Context() context.Context // Deprecated: See ClientStream and ServerStream documentation instead. SendMsg(m interface{}) error // Deprecated: See ClientStream and ServerStream documentation instead. RecvMsg(m interface{}) error }
Stream defines the common interface a client or server stream has to satisfy.
Deprecated: See ClientStream and ServerStream documentation instead.
type 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.
type 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.
type 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. If a StreamHandler returns an error, it should be produced by the status package, or else gRPC will use codes.Unknown as the status code and err.Error() as the status message of the RPC.
type 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.
type 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.
type 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.
type TrailerCallOption ¶
TrailerCallOption is a CallOption for collecting response trailer metadata. The metadata field will be populated *after* the RPC completes. This is an EXPERIMENTAL API.
type 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.
type UnaryHandler ¶
UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal execution of a unary RPC. If a UnaryHandler returns an error, it should be produced by the status package, or else gRPC will use codes.Unknown as the status code and err.Error() as the status message of the RPC.
type 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.
type 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.
type 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.
Source Files ¶
- backoff.go
- balancer.go
- balancer_conn_wrappers.go
- balancer_v1_wrapper.go
- call.go
- clientconn.go
- codec.go
- conn.go
- dialoptions.go
- doc.go
- interceptor.go
- picker_wrapper.go
- pickfirst.go
- preloader.go
- proxy.go
- resolver_conn_wrapper.go
- rpc_util.go
- server.go
- service_config.go
- stream.go
- trace.go
- transfer.go
- version.go
Directories ¶
Path | Synopsis |
---|---|
Package attributes defines a generic key/value store used in various gRPC components.
|
Package attributes defines a generic key/value store used in various gRPC components. |
Package backoff provides configuration options for backoff.
|
Package backoff provides configuration options for backoff. |
Package balancer defines APIs for load balancing in gRPC.
|
Package balancer defines APIs for load balancing in gRPC. |
base
Package base defines a balancer base that can be used to build balancers with different picking algorithms.
|
Package base defines a balancer base that can be used to build balancers with different picking algorithms. |
grpclb
Package grpclb defines a grpclb balancer.
|
Package grpclb defines a grpclb balancer. |
rls/internal
Package rls implements the RLS LB policy.
|
Package rls implements the RLS LB policy. |
rls/internal/adaptive
Package adaptive provides functionality for adaptive client-side throttling.
|
Package adaptive provides functionality for adaptive client-side throttling. |
rls/internal/cache
Package cache provides an LRU cache implementation to be used by the RLS LB policy to cache RLS response data.
|
Package cache provides an LRU cache implementation to be used by the RLS LB policy to cache RLS response data. |
rls/internal/keys
Package keys provides functionality required to build RLS request keys.
|
Package keys provides functionality required to build RLS request keys. |
roundrobin
Package roundrobin defines a roundrobin balancer.
|
Package roundrobin defines a roundrobin balancer. |
weightedroundrobin
Package weightedroundrobin defines a weighted roundrobin balancer.
|
Package weightedroundrobin defines a weighted roundrobin balancer. |
Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks.
|
Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks. |
benchmain
Package main provides benchmark with setting flags.
|
Package main provides benchmark with setting flags. |
benchresult
To format the benchmark result: go run benchmark/benchresult/main.go resultfile To see the performance change based on a old result: go run benchmark/benchresult/main.go resultfile_old resultfile It will print the comparison result of intersection benchmarks between two files.
|
To format the benchmark result: go run benchmark/benchresult/main.go resultfile To see the performance change based on a old result: go run benchmark/benchresult/main.go resultfile_old resultfile It will print the comparison result of intersection benchmarks between two files. |
client
Package main provides a client used for benchmarking.
|
Package main provides a client used for benchmarking. |
flags
Package flags provide convenience types and routines to accept specific types of flag values on the command line.
|
Package flags provide convenience types and routines to accept specific types of flag values on the command line. |
latency
Package latency provides wrappers for net.Conn, net.Listener, and net.Dialers, designed to interoperate to inject real-world latency into network connections.
|
Package latency provides wrappers for net.Conn, net.Listener, and net.Dialers, designed to interoperate to inject real-world latency into network connections. |
server
Package main provides a server used for benchmarking.
|
Package main provides a server used for benchmarking. |
stats
Package stats tracks the statistics associated with benchmark runs.
|
Package stats tracks the statistics associated with benchmark runs. |
channelz
|
|
service
Package service provides an implementation for channelz service server.
|
Package service provides an implementation for channelz service server. |
Package codes defines the canonical error codes used by gRPC.
|
Package codes defines the canonical error codes used by gRPC. |
Package connectivity defines connectivity semantics.
|
Package connectivity defines connectivity semantics. |
Package credentials implements various credentials supported by gRPC library, which encapsulate all the state needed by a client to authenticate with a server and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call.
|
Package credentials implements various credentials supported by gRPC library, which encapsulate all the state needed by a client to authenticate with a server and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call. |
alts
Package alts implements the ALTS credential support by gRPC library, which encapsulates all the state needed by a client to authenticate with a server using ALTS and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call.
|
Package alts implements the ALTS credential support by gRPC library, which encapsulates all the state needed by a client to authenticate with a server using ALTS and make various assertions, e.g., about the client's identity, role, or whether it is authorized to make a particular call. |
alts/internal
Package internal contains common core functionality for ALTS.
|
Package internal contains common core functionality for ALTS. |
alts/internal/authinfo
Package authinfo provide authentication information returned by handshakers.
|
Package authinfo provide authentication information returned by handshakers. |
alts/internal/conn
Package conn contains an implementation of a secure channel created by gRPC handshakers.
|
Package conn contains an implementation of a secure channel created by gRPC handshakers. |
alts/internal/handshaker
Package handshaker provides ALTS handshaking functionality for GCP.
|
Package handshaker provides ALTS handshaking functionality for GCP. |
alts/internal/handshaker/service
Package service manages connections between the VM application and the ALTS handshaker service.
|
Package service manages connections between the VM application and the ALTS handshaker service. |
alts/internal/testutil
Package testutil include useful test utilities for the handshaker.
|
Package testutil include useful test utilities for the handshaker. |
google
Package google defines credentials for google cloud services.
|
Package google defines credentials for google cloud services. |
internal
Package internal contains credentials-internal code.
|
Package internal contains credentials-internal code. |
oauth
Package oauth implements gRPC credentials using OAuth.
|
Package oauth implements gRPC credentials using OAuth. |
Package encoding defines the interface for the compressor and codec, and functions to register and retrieve compressors and codecs.
|
Package encoding defines the interface for the compressor and codec, and functions to register and retrieve compressors and codecs. |
gzip
Package gzip implements and registers the gzip compressor during the initialization.
|
Package gzip implements and registers the gzip compressor during the initialization. |
proto
Package proto defines the protobuf codec.
|
Package proto defines the protobuf codec. |
examples
|
|
features/authentication/client
The client demonstrates how to supply an OAuth2 token for every RPC.
|
The client demonstrates how to supply an OAuth2 token for every RPC. |
features/authentication/server
The server demonstrates how to consume and validate OAuth2 tokens provided by clients for each RPC.
|
The server demonstrates how to consume and validate OAuth2 tokens provided by clients for each RPC. |
features/cancellation/client
Binary client is an example client.
|
Binary client is an example client. |
features/cancellation/server
Binary server is an example server.
|
Binary server is an example server. |
features/compression/client
Binary client is an example client.
|
Binary client is an example client. |
features/compression/server
Binary server is an example server.
|
Binary server is an example server. |
features/deadline/client
Binary client is an example client.
|
Binary client is an example client. |
features/deadline/server
Binary server is an example server.
|
Binary server is an example server. |
features/debugging/client
Binary client is an example client.
|
Binary client is an example client. |
features/debugging/server
Binary server is an example server.
|
Binary server is an example server. |
features/encryption/ALTS/client
Binary client is an example client.
|
Binary client is an example client. |
features/encryption/ALTS/server
Binary server is an example server.
|
Binary server is an example server. |
features/encryption/TLS/client
Binary client is an example client.
|
Binary client is an example client. |
features/encryption/TLS/server
Binary server is an example server.
|
Binary server is an example server. |
features/errors/client
Binary client is an example client.
|
Binary client is an example client. |
features/errors/server
Binary server is an example server.
|
Binary server is an example server. |
features/interceptor/client
Binary client is an example client.
|
Binary client is an example client. |
features/interceptor/server
Binary server is an example server.
|
Binary server is an example server. |
features/keepalive/client
Binary client is an example client.
|
Binary client is an example client. |
features/keepalive/server
Binary server is an example server.
|
Binary server is an example server. |
features/load_balancing/client
Binary client is an example client.
|
Binary client is an example client. |
features/load_balancing/server
Binary server is an example server.
|
Binary server is an example server. |
features/metadata/client
Binary client is an example client.
|
Binary client is an example client. |
features/metadata/server
Binary server is an example server.
|
Binary server is an example server. |
features/multiplex/client
Binary client is an example client.
|
Binary client is an example client. |
features/multiplex/server
Binary server is an example server.
|
Binary server is an example server. |
features/name_resolving/client
Binary client is an example client.
|
Binary client is an example client. |
features/name_resolving/server
Binary server is an example server.
|
Binary server is an example server. |
features/profiling/client
Binary client is an example client.
|
Binary client is an example client. |
features/profiling/server
Binary server is an example server.
|
Binary server is an example server. |
features/proto
Package proto is for go generate.
|
Package proto is for go generate. |
features/reflection/server
Binary server is an example server.
|
Binary server is an example server. |
features/retry/client
Binary client is an example client.
|
Binary client is an example client. |
features/retry/server
Binary server is an example server.
|
Binary server is an example server. |
features/wait_for_ready
Binary wait_for_ready is an example for "wait for ready".
|
Binary wait_for_ready is an example for "wait for ready". |
features/xds/client
Package main implements a client for Greeter service.
|
Package main implements a client for Greeter service. |
features/xds/server
Package main starts Greeter service that will response with the hostname.
|
Package main starts Greeter service that will response with the hostname. |
helloworld/greeter_client
Package main implements a client for Greeter service.
|
Package main implements a client for Greeter service. |
helloworld/greeter_server
Package main implements a server for Greeter service.
|
Package main implements a server for Greeter service. |
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.
|
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. |
route_guide/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.
|
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. |
Package grpclog defines logging for grpc.
|
Package grpclog defines logging for grpc. |
glogger
Package glogger defines glog-based logging for grpc.
|
Package glogger defines glog-based logging for grpc. |
Package health provides a service that exposes server's health and it must be imported to enable support for client-side health checks.
|
Package health provides a service that exposes server's health and it must be imported to enable support for client-side health checks. |
Package internal contains gRPC-internal code, to avoid polluting the godoc of the top-level grpc package.
|
Package internal contains gRPC-internal code, to avoid polluting the godoc of the top-level grpc package. |
backoff
Package backoff implement the backoff strategy for gRPC.
|
Package backoff implement the backoff strategy for gRPC. |
balancerload
Package balancerload defines APIs to parse server loads in trailers.
|
Package balancerload defines APIs to parse server loads in trailers. |
binarylog
Package binarylog implementation binary logging as defined in https://github.com/grpc/proposal/blob/master/A16-binary-logging.md.
|
Package binarylog implementation binary logging as defined in https://github.com/grpc/proposal/blob/master/A16-binary-logging.md. |
buffer
Package buffer provides an implementation of an unbounded buffer.
|
Package buffer provides an implementation of an unbounded buffer. |
cache
Package cache implements caches to be used in gRPC.
|
Package cache implements caches to be used in gRPC. |
channelz
Package channelz defines APIs for enabling channelz service, entry registration/deletion, and accessing channelz data.
|
Package channelz defines APIs for enabling channelz service, entry registration/deletion, and accessing channelz data. |
envconfig
Package envconfig contains grpc settings configured by environment variables.
|
Package envconfig contains grpc settings configured by environment variables. |
grpclog
Package grpclog (internal) defines depth logging for grpc.
|
Package grpclog (internal) defines depth logging for grpc. |
grpcrand
Package grpcrand implements math/rand functions in a concurrent-safe way with a global random source, independent of math/rand's global source.
|
Package grpcrand implements math/rand functions in a concurrent-safe way with a global random source, independent of math/rand's global source. |
grpcsync
Package grpcsync implements additional synchronization primitives built upon the sync package.
|
Package grpcsync implements additional synchronization primitives built upon the sync package. |
grpctest
Package grpctest implements testing helpers.
|
Package grpctest implements testing helpers. |
grpcutil
Package grpcutil provides a bunch of utility functions to be used across the gRPC codebase.
|
Package grpcutil provides a bunch of utility functions to be used across the gRPC codebase. |
leakcheck
Package leakcheck contains functions to check leaked goroutines.
|
Package leakcheck contains functions to check leaked goroutines. |
profiling
Package profiling contains two logical components: buffer.go and profiling.go.
|
Package profiling contains two logical components: buffer.go and profiling.go. |
profiling/buffer
Package buffer provides a high-performant lock free implementation of a circular buffer used by the profiling code.
|
Package buffer provides a high-performant lock free implementation of a circular buffer used by the profiling code. |
resolver/dns
Package dns implements a dns resolver to be installed as the default resolver in grpc.
|
Package dns implements a dns resolver to be installed as the default resolver in grpc. |
resolver/passthrough
Package passthrough implements a pass-through resolver.
|
Package passthrough implements a pass-through resolver. |
syscall
Package syscall provides functionalities that grpc uses to get low-level operating system stats/info.
|
Package syscall provides functionalities that grpc uses to get low-level operating system stats/info. |
testutils
Package testutils contains testing helpers.
|
Package testutils contains testing helpers. |
transport
Package transport defines and implements message oriented communication channel to complete various transactions (e.g., an RPC).
|
Package transport defines and implements message oriented communication channel to complete various transactions (e.g., an RPC). |
alts/client
This binary can only run on Google Cloud Platform (GCP).
|
This binary can only run on Google Cloud Platform (GCP). |
alts/server
This binary can only run on Google Cloud Platform (GCP).
|
This binary can only run on Google Cloud Platform (GCP). |
fake_grpclb
This file is for testing only.
|
This file is for testing only. |
xds/client
Binary client for xDS interop tests.
|
Binary client for xDS interop tests. |
xds/server
Binary server for xDS interop tests.
|
Binary server for xDS interop tests. |
Package keepalive defines configurable parameters for point-to-point healthcheck.
|
Package keepalive defines configurable parameters for point-to-point healthcheck. |
Package metadata define the structure of the metadata supported by gRPC library.
|
Package metadata define the structure of the metadata supported by gRPC library. |
Package naming defines the naming API and related data structures for gRPC.
|
Package naming defines the naming API and related data structures for gRPC. |
Package peer defines various peer information associated with RPCs and corresponding utils.
|
Package peer defines various peer information associated with RPCs and corresponding utils. |
Package profiling exposes methods to manage profiling within gRPC.
|
Package profiling exposes methods to manage profiling within gRPC. |
cmd
Binary cmd is a command-line tool for profiling management.
|
Binary cmd is a command-line tool for profiling management. |
service
Package service defines methods to register a gRPC client/service for a profiling service that is exposed in the same server.
|
Package service defines methods to register a gRPC client/service for a profiling service that is exposed in the same server. |
Package reflection implements server reflection service.
|
Package reflection implements server reflection service. |
grpc_testingv3
Package grpc_testingv3 is a generated protocol buffer package.
|
Package grpc_testingv3 is a generated protocol buffer package. |
Package resolver defines APIs for name resolution in gRPC.
|
Package resolver defines APIs for name resolution in gRPC. |
dns
Package dns implements a dns resolver to be installed as the default resolver in grpc.
|
Package dns implements a dns resolver to be installed as the default resolver in grpc. |
manual
Package manual defines a resolver that can be used to manually send resolved addresses to ClientConn.
|
Package manual defines a resolver that can be used to manually send resolved addresses to ClientConn. |
passthrough
Package passthrough implements a pass-through resolver.
|
Package passthrough implements a pass-through resolver. |
Package serviceconfig defines types and methods for operating on gRPC service configs.
|
Package serviceconfig defines types and methods for operating on gRPC service configs. |
Package stats is for collecting and reporting various network and RPC stats.
|
Package stats is for collecting and reporting various network and RPC stats. |
Package status implements errors returned by gRPC.
|
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.
|
client starts an interop client to do stress test and a metrics server to report qps. |
Package tap defines the function handles which are executed on the transport layer of gRPC-Go and related information.
|
Package tap defines the function handles which are executed on the transport layer of gRPC-Go and related information. |
bufconn
Package bufconn provides a net.Conn implemented by a buffer and related dialing and listening functionality.
|
Package bufconn provides a net.Conn implemented by a buffer and related dialing and listening functionality. |
go_vet
vet checks whether files that are supposed to be built on appengine running Go 1.10 or earlier import an unsupported package (e.g.
|
vet checks whether files that are supposed to be built on appengine running Go 1.10 or earlier import an unsupported package (e.g. |
xds
|
|
experimental
Package experimental contains xds implementation, still in experimental state.
|
Package experimental contains xds implementation, still in experimental state. |
internal/balancer
Package balancer installs all the xds balancers.
|
Package balancer installs all the xds balancers. |
internal/balancer/cdsbalancer
Package cdsbalancer implements a balancer to handle CDS responses.
|
Package cdsbalancer implements a balancer to handle CDS responses. |
internal/balancer/edsbalancer
Package edsbalancer contains EDS balancer implementation.
|
Package edsbalancer contains EDS balancer implementation. |
internal/balancer/lrs
Package lrs implements load reporting service for xds balancer.
|
Package lrs implements load reporting service for xds balancer. |
internal/balancer/orca
Package orca implements Open Request Cost Aggregation.
|
Package orca implements Open Request Cost Aggregation. |
internal/client
Package client implementation a full fledged gRPC client for the xDS API used by the xds resolver and balancer implementations.
|
Package client implementation a full fledged gRPC client for the xDS API used by the xds resolver and balancer implementations. |
internal/client/bootstrap
Package bootstrap provides the functionality to initialize certain aspects of an xDS client by reading a bootstrap file.
|
Package bootstrap provides the functionality to initialize certain aspects of an xDS client by reading a bootstrap file. |
internal/proto
Package proto is for go generate.
|
Package proto is for go generate. |
internal/resolver
Package resolver implements the xds resolver, that does LDS and RDS to find the cluster to use.
|
Package resolver implements the xds resolver, that does LDS and RDS to find the cluster to use. |
internal/testutils
Package testutils provides utility types, for use in xds tests.
|
Package testutils provides utility types, for use in xds tests. |
internal/testutils/fakeclient
Package fakeclient provides a fake implementation of an xDS client.
|
Package fakeclient provides a fake implementation of an xDS client. |
internal/testutils/fakeserver
Package fakeserver provides a fake implementation of an xDS server.
|
Package fakeserver provides a fake implementation of an xDS server. |