Server
rpcx
// Server is rpcx server that use TCP or UDP.type Server struct {ln net.ListenerreadTimeout time.DurationwriteTimeout time.DurationgatewayHTTPServer *http.ServerDisableHTTPGateway bool // should disable http invoke or not.DisableJSONRPC bool // should disable json rpc or not.serviceMapMu sync.RWMutexserviceMap map[string]*servicemu sync.RWMutexactiveConn map[net.Conn]struct{}doneChan chan struct{}seq uint64inShutdown int32onShutdown []func(s *Server)// TLSConfig for creating tls tcp connection.tlsConfig *tls.Config// BlockCrypt for kcp.BlockCryptoptions map[string]interface{}// CORS optionscorsOptions *CORSOptionsPlugins PluginContainer// AuthFunc can be used to auth.AuthFunc func(ctx context.Context, req *protocol.Message, token string) errorhandlerMsgNum int32}
gorilla/rpc
// Server serves registered RPC services using registered codecs.type Server struct {codecs map[string]Codecservices *serviceMapinterceptFunc func(i *RequestInfo) *http.RequestbeforeFunc func(i *RequestInfo)afterFunc func(i *RequestInfo)}
grpc-go
// Server is a gRPC server to serve RPC requests.type Server struct {opts serverOptionsmu sync.Mutex // guards followinglis map[net.Listener]boolconns map[transport.ServerTransport]boolserve booldrain boolcv *sync.Cond // signaled when connections close for GracefulStopm map[string]*service // service name -> service infoevents trace.EventLogquit *grpcsync.Eventdone *grpcsync.EventchannelzRemoveOnce sync.OnceserveWG sync.WaitGroup // counts active Serve goroutines for GracefulStopchannelzID int64 // channelz unique identification numberczData *channelzData}
Client
rpcx
// RPCClient is interface that defines one client to call one server.type RPCClient interface {Connect(network, address string) errorGo(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, done chan *Call) *CallCall(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}) errorSendRaw(ctx context.Context, r *protocol.Message) (map[string]string, []byte, error)Close() errorRegisterServerMessageChan(ch chan<- *protocol.Message)UnregisterServerMessageChan()IsClosing() boolIsShutdown() bool}
// Client represents a RPC client.type Client struct {option OptionConn net.Connr *bufio.Reader//w *bufio.Writermutex sync.Mutex // protects followingseq uint64pending map[uint64]*Callclosing bool // user has called Closeshutdown bool // server has told us to stoppluginClosed bool // the plugin has been calledPlugins PluginContainerServerMessageChan chan<- *protocol.Message}
grpc-go
// ClientConn represents a client connection to an RPC server.type ClientConn struct {ctx context.Contextcancel context.CancelFunctarget stringparsedTarget resolver.Targetauthority stringdopts dialOptionscsMgr *connectivityStateManagerbalancerBuildOpts balancer.BuildOptionsblockingpicker *pickerWrappermu sync.RWMutexresolverWrapper *ccResolverWrappersc *ServiceConfigconns map[*addrConn]struct{}// Keepalive parameter can be updated if a GoAway is received.mkp keepalive.ClientParameterscurBalancerName stringbalancerWrapper *ccBalancerWrapperretryThrottler atomic.ValuefirstResolveEvent *grpcsync.EventchannelzID int64 // channelz unique identification numberczData *channelzData}
Codec
rpcx
// Codec defines the interface that decode/encode payload.type Codec interface {Encode(i interface{}) ([]byte, error)Decode(data []byte, i interface{}) error}
gorilla/rpc
// Codec creates a CodecRequest to process each request.type Codec interface {NewRequest(*http.Request) CodecRequest}// CodecRequest decodes a request and encodes a response using a specific// serialization scheme.type CodecRequest interface {// Reads request and returns the RPC method name.Method() (string, error)// Reads request filling the RPC method args.ReadRequest(interface{}) error// Writes response using the RPC method reply. The error parameter is// the error returned by the method call, if any.WriteResponse(http.ResponseWriter, interface{}, error) error}
Service
rpcx
type methodType struct {sync.Mutex // protects countersmethod reflect.MethodArgType reflect.TypeReplyType reflect.Type// numCalls uint}type functionType struct {sync.Mutex // protects countersfn reflect.ValueArgType reflect.TypeReplyType reflect.Type}type service struct {name string // name of servicercvr reflect.Value // receiver of methods for the servicetyp reflect.Type // type of the receivermethod map[string]*methodType // registered methodsfunction map[string]*functionType // registered functions}
gorilla/rpc
type service struct {name string // name of servicercvr reflect.Value // receiver of methods for the servicercvrType reflect.Type // type of the receivermethods map[string]*serviceMethod // registered methodspassReq bool}type serviceMethod struct {method reflect.Method // receiver methodargsType reflect.Type // type of the request argumentreplyType reflect.Type // type of the response argument}
grpc-go
// MethodDesc represents an RPC service's method specification.type MethodDesc struct {MethodName stringHandler methodHandler}// ServiceDesc represents an RPC service's specification.type ServiceDesc struct {ServiceName string// The pointer to the service interface. Used to check whether the user// provided implementation satisfies the interface requirements.HandlerType interface{}Methods []MethodDescStreams []StreamDescMetadata interface{}}// service consists of the information of the server serving this service and// the methods in this service.type service struct {server interface{} // the server for service methodsmd map[string]*MethodDescsd map[string]*StreamDescmdata interface{}}
Option
grpc-go
// A ServerOption sets options such as credentials, codec and keepalive parameters, etc.type ServerOption interface {apply(*serverOptions)}type serverOptions struct {creds credentials.TransportCredentialscodec baseCodeccp Compressordc DecompressorunaryInt UnaryServerInterceptorstreamInt StreamServerInterceptorinTapHandle tap.ServerInHandlestatsHandler stats.HandlermaxConcurrentStreams uint32maxReceiveMessageSize intmaxSendMessageSize intunknownStreamDesc *StreamDesckeepaliveParams keepalive.ServerParameterskeepalivePolicy keepalive.EnforcementPolicyinitialWindowSize int32initialConnWindowSize int32writeBufferSize intreadBufferSize intconnectionTimeout time.DurationmaxHeaderListSize *uint32}
Connection
rpcx
tcp
var makeListeners = make(map[string]MakeListener)func init() {makeListeners["tcp"] = tcpMakeListener("tcp")makeListeners["tcp4"] = tcpMakeListener("tcp4")makeListeners["tcp6"] = tcpMakeListener("tcp6")makeListeners["http"] = tcpMakeListener("tcp")}// RegisterMakeListener registers a MakeListener for network.func RegisterMakeListener(network string, ml MakeListener) {makeListeners[network] = ml}// MakeListener defines a listener generater.type MakeListener func(s *Server, address string) (ln net.Listener, err error)// block can be nil if the caller wishes to skip encryption in kcp.// tlsConfig can be nil iff we are not using network "quic".func (s *Server) makeListener(network, address string) (ln net.Listener, err error) {ml := makeListeners[network]if ml == nil {return nil, fmt.Errorf("can not make listener for %s", network)}return ml(s, address)}func tcpMakeListener(network string) func(s *Server, address string) (ln net.Listener, err error) {return func(s *Server, address string) (ln net.Listener, err error) {if s.tlsConfig == nil {ln, err = net.Listen(network, address)} else {ln, err = tls.Listen(network, address, s.tlsConfig)}return ln, err}}
quic
quicconn “github.com/marten-seemann/quic-conn”
func init() {makeListeners["quic"] = quicMakeListener}func quicMakeListener(s *Server, address string) (ln net.Listener, err error) {if s.tlsConfig == nil {return nil, errors.New("TLSConfig must be configured in server.Options")}return quicconn.Listen("udp", address, s.tlsConfig)}
utp
“github.com/anacrolix/utp”
func init() {makeListeners["utp"] = utpMakeListener}func utpMakeListener(s *Server, address string) (ln net.Listener, err error) {return utp.Listen(address)}
kcp
import kcp “github.com/xtaci/kcp-go”
func init() {makeListeners["kcp"] = kcpMakeListener}func kcpMakeListener(s *Server, address string) (ln net.Listener, err error) {if s.options == nil || s.options["BlockCrypt"] == nil {return nil, errors.New("KCP BlockCrypt must be configured in server.Options")}return kcp.ListenWithOptions(address, s.options["BlockCrypt"].(kcp.BlockCrypt), 10, 3)}// WithBlockCrypt sets kcp.BlockCrypt.func WithBlockCrypt(bc kcp.BlockCrypt) OptionFn {return func(s *Server) {s.options["BlockCrypt"] = bc}}
