Documentation ¶
Overview ¶
Package rpc implements bi-directional JSON-RPC 2.0 on multiple transports.
It provides access to the exported methods of an object across a network or other I/O connection. After creating a server or client instance, objects can be registered to make them visible as 'services'. Exported methods that follow specific conventions can be called remotely. It also has support for the publish/subscribe pattern.
RPC Methods ¶
Methods that satisfy the following criteria are made available for remote access:
- method must be exported
- method returns 0, 1 (response or error) or 2 (response and error) values
An example method:
func (s *CalcService) Add(a, b int) (int, error)
When the returned error isn't nil the returned integer is ignored and the error is sent back to the client. Otherwise the returned integer is sent back to the client.
Optional arguments are supported by accepting pointer values as arguments. E.g. if we want to do the addition in an optional finite field we can accept a mod argument as pointer value.
func (s *CalcService) Add(a, b int, mod *int) (int, error)
This RPC method can be called with 2 integers and a null value as third argument. In that case the mod argument will be nil. Or it can be called with 3 integers, in that case mod will be pointing to the given third argument. Since the optional argument is the last argument the RPC package will also accept 2 integers as arguments. It will pass the mod argument as nil to the RPC method.
The server offers the ServeCodec method which accepts a ServerCodec instance. It will read requests from the codec, process the request and sends the response back to the client using the codec. The server can execute requests concurrently. Responses can be sent back to the client out of order.
An example server which uses the JSON codec:
type CalculatorService struct {} func (s *CalculatorService) Add(a, b int) int { return a + b } func (s *CalculatorService) Div(a, b int) (int, error) { if b == 0 { return 0, errors.New("divide by zero") } return a/b, nil } calculator := new(CalculatorService) server := NewServer() server.RegisterName("calculator", calculator) l, _ := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: "/tmp/calculator.sock"}) server.ServeListener(l)
Subscriptions ¶
The package also supports the publish subscribe pattern through the use of subscriptions. A method that is considered eligible for notifications must satisfy the following criteria:
- method must be exported
- first method argument type must be context.Context
- method must have return types (rpc.Subscription, error)
An example method:
func (s *BlockChainService) NewBlocks(ctx context.Context) (rpc.Subscription, error) { ... }
When the service containing the subscription method is registered to the server, for example under the "blockchain" namespace, a subscription is created by calling the "blockchain_subscribe" method.
Subscriptions are deleted when the user sends an unsubscribe request or when the connection which was used to create the subscription is closed. This can be initiated by the client and server. The server will close the connection for any write error.
For more information about subscriptions, see https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB.
Reverse Calls ¶
In any method handler, an instance of rpc.Client can be accessed through the ClientFromContext method. Using this client instance, server-to-client method calls can be performed on the RPC connection.
Index ¶
- Constants
- Variables
- func ContextRequestTimeout(ctx context.Context) (time.Duration, bool)
- func NewContextWithHeaders(ctx context.Context, h http.Header) context.Context
- type API
- type BatchElem
- type BlockNumber
- type BlockNumberOrHash
- type Client
- func ClientFromContext(ctx context.Context) (*Client, bool)
- func Dial(rawurl string) (*Client, error)
- func DialContext(ctx context.Context, rawurl string) (*Client, error)
- func DialHTTP(endpoint string) (*Client, error)
- func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error)deprecated
- func DialInProc(handler *Server) *Client
- func DialOptions(ctx context.Context, rawurl string, options ...ClientOption) (*Client, error)
- func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error)
- func DialWebsocketWithDialer(ctx context.Context, endpoint, origin string, dialer websocket.Dialer) (*Client, error)deprecated
- func (c *Client) BatchCall(b []BatchElem) error
- func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error
- func (c *Client) Call(result interface{}, method string, args ...interface{}) error
- func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error
- func (c *Client) Close()
- func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
- func (c *Client) Notify(ctx context.Context, method string, args ...interface{}) error
- func (c *Client) RegisterName(name string, receiver interface{}) error
- func (c *Client) SetHeader(key, value string)
- func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
- func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, ...) (*ClientSubscription, error)
- func (c *Client) SupportedModules() (map[string]string, error)
- func (c *Client) SupportsSubscriptions() bool
- type ClientOption
- func WithBatchItemLimit(limit int) ClientOption
- func WithBatchResponseSizeLimit(sizeLimit int) ClientOption
- func WithHTTPAuth(a HTTPAuth) ClientOption
- func WithHTTPClient(c *http.Client) ClientOption
- func WithHeader(key, value string) ClientOption
- func WithHeaders(headers http.Header) ClientOption
- func WithWebsocketDialer(dialer websocket.Dialer) ClientOption
- func WithWebsocketMessageSizeLimit(messageSizeLimit int64) ClientOption
- type ClientSubscription
- type CodecOptiondeprecated
- type Conn
- type ConnRemoteAddr
- type DataError
- type Error
- type HTTPAuth
- type HTTPError
- type HTTPTimeouts
- type ID
- type Notifier
- type PeerInfo
- type RPCService
- type Server
- func (s *Server) RegisterName(name string, receiver interface{}) error
- func (s *Server) ServeCodec(codec ServerCodec, options CodecOption, ...)
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) SetBatchLimits(itemLimit, maxResponseSize int)
- func (s *Server) Stop()
- func (s *Server) WebsocketHandler(allowedOrigins []string) http.Handler
- func (s *Server) WebsocketHandlerWithDuration(allowedOrigins []string, apiMaxDuration, refillRate, maxStored time.Duration) http.Handler
- type ServerCodec
- type Subscription
Examples ¶
Constants ¶
const ( SafeBlockNumber = BlockNumber(-4) FinalizedBlockNumber = BlockNumber(-3) LatestBlockNumber = BlockNumber(-2) PendingBlockNumber = BlockNumber(-1) EarliestBlockNumber = BlockNumber(0) )
const MetadataApi = "rpc"
Variables ¶
var ( ErrBadResult = errors.New("bad result in JSON-RPC response") ErrClientQuit = errors.New("client is closed") ErrNoResult = errors.New("JSON-RPC response has no result") ErrMissingBatchResponse = errors.New("response batch did not contain a response to this call") ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow") )
var ( // ErrNotificationsUnsupported is returned by the client when the connection doesn't // support notifications. You can use this error value to check for subscription // support like this: // // sub, err := client.EthSubscribe(ctx, channel, "newHeads", true) // if errors.Is(err, rpc.ErrNotificationsUnsupported) { // // Server does not support subscriptions, fall back to polling. // } // ErrNotificationsUnsupported = notificationsUnsupportedError{} // ErrSubscriptionNotFound is returned when the notification for the given id is not found ErrSubscriptionNotFound = errors.New("subscription not found") )
var DefaultHTTPTimeouts = HTTPTimeouts{ ReadTimeout: 30 * time.Second, ReadHeaderTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second, }
DefaultHTTPTimeouts represents the default timeout values used if further configuration is not provided.
Functions ¶
func ContextRequestTimeout ¶ added in v0.12.3
ContextRequestTimeout returns the request timeout derived from the given context.
Types ¶
type API ¶ added in v0.8.13
type API struct { Namespace string // namespace under which the rpc methods of Service are exposed Version string // deprecated - this field is no longer used, but retained for compatibility Service interface{} // receiver instance which holds the methods Name string // Name of the API }
API describes the set of methods offered over the RPC interface
type BatchElem ¶ added in v0.8.13
type BatchElem struct { Method string Args []interface{} // The result is unmarshaled into this field. Result must be set to a // non-nil pointer value of the desired type, otherwise the response will be // discarded. Result interface{} // Error is set if the server returns an error for this request, or if // unmarshaling into Result fails. It is not set for I/O errors. Error error }
BatchElem is an element in a batch request.
type BlockNumber ¶
type BlockNumber int64
func (BlockNumber) Int64 ¶
func (bn BlockNumber) Int64() int64
Int64 returns the block number as int64.
func (BlockNumber) IsAccepted ¶ added in v0.8.13
func (bn BlockNumber) IsAccepted() bool
IsAccepted returns true if this blockNumber should be treated as a request for the last accepted block
func (BlockNumber) IsLatest ¶
func (bn BlockNumber) IsLatest() bool
func (BlockNumber) MarshalText ¶ added in v0.8.13
func (bn BlockNumber) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler. It marshals: - "accepted", "latest", "earliest" or "pending" as strings - other numbers as hex
func (BlockNumber) String ¶ added in v0.12.5
func (bn BlockNumber) String() string
func (*BlockNumber) UnmarshalJSON ¶
func (bn *BlockNumber) UnmarshalJSON(data []byte) error
UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports: - "accepted", "safe", "finalized", "latest", "earliest" or "pending" as string arguments - the block number Returned errors: - an invalid block number error when the given argument isn't a known strings - an out of range error when the given block number is either too little or too large
type BlockNumberOrHash ¶ added in v0.8.13
type BlockNumberOrHash struct { BlockNumber *BlockNumber `json:"blockNumber,omitempty"` BlockHash *common.Hash `json:"blockHash,omitempty"` RequireCanonical bool `json:"requireCanonical,omitempty"` }
func BlockNumberOrHashWithHash ¶ added in v0.8.13
func BlockNumberOrHashWithHash(hash common.Hash, canonical bool) BlockNumberOrHash
func BlockNumberOrHashWithNumber ¶ added in v0.8.13
func BlockNumberOrHashWithNumber(blockNr BlockNumber) BlockNumberOrHash
func (*BlockNumberOrHash) Hash ¶ added in v0.8.13
func (bnh *BlockNumberOrHash) Hash() (common.Hash, bool)
func (*BlockNumberOrHash) Number ¶ added in v0.8.13
func (bnh *BlockNumberOrHash) Number() (BlockNumber, bool)
func (*BlockNumberOrHash) String ¶ added in v0.8.13
func (bnh *BlockNumberOrHash) String() string
func (*BlockNumberOrHash) UnmarshalJSON ¶ added in v0.8.13
func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error
type Client ¶ added in v0.8.13
type Client struct {
// contains filtered or unexported fields
}
Client represents a connection to an RPC server.
func ClientFromContext ¶ added in v0.8.13
ClientFromContext retrieves the client from the context, if any. This can be used to perform 'reverse calls' in a handler method.
func Dial ¶ added in v0.8.13
Dial creates a new client for the given URL.
The currently supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a file name with no URL scheme, a local socket connection is established using UNIX domain sockets on supported platforms and named pipes on Windows.
If you want to further configure the transport, use DialOptions instead of this function.
For websocket connections, the origin is set to the local host name.
The client reconnects automatically when the connection is lost.
func DialContext ¶ added in v0.8.13
DialContext creates a new RPC client, just like Dial.
The context is used to cancel or time out the initial connection establishment. It does not affect subsequent interactions with the client.
func DialHTTP ¶ added in v0.8.13
DialHTTP creates a new RPC client that connects to an RPC server over HTTP.
func DialHTTPWithClient
deprecated
added in
v0.8.13
func DialInProc ¶ added in v0.8.13
DialInProc attaches an in-process connection to the given RPC server.
func DialOptions ¶ added in v0.12.1
DialOptions creates a new RPC client for the given URL. You can supply any of the pre-defined client options to configure the underlying transport.
The context is used to cancel or time out the initial connection establishment. It does not affect subsequent interactions with the client.
The client reconnects automatically when the connection is lost.
Example ¶
This example configures a HTTP-based RPC client with two options - one setting the overall request timeout, the other adding a custom HTTP header to all requests.
package main import ( "context" "net/http" "time" "github.com/MetalBlockchain/coreth/rpc" ) func main() { tokenHeader := rpc.WithHeader("x-token", "foo") httpClient := rpc.WithHTTPClient(&http.Client{ Timeout: 10 * time.Second, }) ctx := context.Background() c, err := rpc.DialOptions(ctx, "http://rpc.example.com", httpClient, tokenHeader) if err != nil { panic(err) } c.Close() }
Output:
func DialWebsocket ¶ added in v0.8.13
DialWebsocket creates a new RPC client that communicates with a JSON-RPC server that is listening on the given endpoint.
The context is used for the initial connection establishment. It does not affect subsequent interactions with the client.
func DialWebsocketWithDialer
deprecated
added in
v0.8.13
func DialWebsocketWithDialer(ctx context.Context, endpoint, origin string, dialer websocket.Dialer) (*Client, error)
DialWebsocketWithDialer creates a new RPC client using WebSocket.
The context is used for the initial connection establishment. It does not affect subsequent interactions with the client.
Deprecated: use DialOptions and the WithWebsocketDialer option.
func (*Client) BatchCall ¶ added in v0.8.13
BatchCall sends all given requests as a single batch and waits for the server to return a response for all of them.
In contrast to Call, BatchCall only returns I/O errors. Any error specific to a request is reported through the Error field of the corresponding BatchElem.
Note that batch calls may not be executed atomically on the server side.
func (*Client) BatchCallContext ¶ added in v0.8.13
BatchCallContext sends all given requests as a single batch and waits for the server to return a response for all of them. The wait duration is bounded by the context's deadline.
In contrast to CallContext, BatchCallContext only returns errors that have occurred while sending the request. Any error specific to a request is reported through the Error field of the corresponding BatchElem.
Note that batch calls may not be executed atomically on the server side.
func (*Client) Call ¶ added in v0.8.13
Call performs a JSON-RPC call with the given arguments and unmarshals into result if no error occurred.
The result must be a pointer so that package json can unmarshal into it. You can also pass nil, in which case the result is ignored.
func (*Client) CallContext ¶ added in v0.8.13
func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error
CallContext performs a JSON-RPC call with the given arguments. If the context is canceled before the call has successfully returned, CallContext returns immediately.
The result must be a pointer so that package json can unmarshal into it. You can also pass nil, in which case the result is ignored.
func (*Client) Close ¶ added in v0.8.13
func (c *Client) Close()
Close closes the client, aborting any in-flight requests.
func (*Client) EthSubscribe ¶ added in v0.8.13
func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
EthSubscribe registers a subscription under the "eth" namespace.
func (*Client) Notify ¶ added in v0.8.13
Notify sends a notification, i.e. a method call that doesn't expect a response.
func (*Client) RegisterName ¶ added in v0.8.13
RegisterName creates a service for the given receiver type under the given name. When no methods on the given receiver match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is created and added to the service collection this client provides to the server.
func (*Client) SetHeader ¶ added in v0.8.13
SetHeader adds a custom HTTP header to the client's requests. This method only works for clients using HTTP, it doesn't have any effect for clients using another transport.
func (*Client) ShhSubscribe ¶ added in v0.8.13
func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
ShhSubscribe registers a subscription under the "shh" namespace. Deprecated: use Subscribe(ctx, "shh", ...).
func (*Client) Subscribe ¶ added in v0.8.13
func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error)
Subscribe calls the "<namespace>_subscribe" method with the given arguments, registering a subscription. Server notifications for the subscription are sent to the given channel. The element type of the channel must match the expected type of content returned by the subscription.
The context argument cancels the RPC request that sets up the subscription but has no effect on the subscription after Subscribe has returned.
Slow subscribers will be dropped eventually. Client buffers up to 20000 notifications before considering the subscriber dead. The subscription Err channel will receive ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure that the channel usually has at least one reader to prevent this issue.
func (*Client) SupportedModules ¶ added in v0.8.13
SupportedModules calls the rpc_modules method, retrieving the list of APIs that are available on the server.
func (*Client) SupportsSubscriptions ¶
SupportsSubscriptions reports whether subscriptions are supported by the client transport. When this returns false, Subscribe and related methods will return ErrNotificationsUnsupported.
type ClientOption ¶ added in v0.12.1
type ClientOption interface {
// contains filtered or unexported methods
}
ClientOption is a configuration option for the RPC client.
func WithBatchItemLimit ¶
func WithBatchItemLimit(limit int) ClientOption
WithBatchItemLimit changes the maximum number of items allowed in batch requests.
Note: this option applies when processing incoming batch requests. It does not affect batch requests sent by the client.
func WithBatchResponseSizeLimit ¶
func WithBatchResponseSizeLimit(sizeLimit int) ClientOption
WithBatchResponseSizeLimit changes the maximum number of response bytes that can be generated for batch requests. When this limit is reached, further calls in the batch will not be processed.
Note: this option applies when processing incoming batch requests. It does not affect batch requests sent by the client.
func WithHTTPAuth ¶ added in v0.12.1
func WithHTTPAuth(a HTTPAuth) ClientOption
WithHTTPAuth configures HTTP request authentication. The given provider will be called whenever a request is made. Note that only one authentication provider can be active at any time.
func WithHTTPClient ¶ added in v0.12.1
func WithHTTPClient(c *http.Client) ClientOption
WithHTTPClient configures the http.Client used by the RPC client.
func WithHeader ¶ added in v0.12.1
func WithHeader(key, value string) ClientOption
WithHeader configures HTTP headers set by the RPC client. Headers set using this option will be used for both HTTP and WebSocket connections.
func WithHeaders ¶ added in v0.12.1
func WithHeaders(headers http.Header) ClientOption
WithHeaders configures HTTP headers set by the RPC client. Headers set using this option will be used for both HTTP and WebSocket connections.
func WithWebsocketDialer ¶ added in v0.12.1
func WithWebsocketDialer(dialer websocket.Dialer) ClientOption
WithWebsocketDialer configures the websocket.Dialer used by the RPC client.
func WithWebsocketMessageSizeLimit ¶
func WithWebsocketMessageSizeLimit(messageSizeLimit int64) ClientOption
WithWebsocketMessageSizeLimit configures the websocket message size limit used by the RPC client. Passing a limit of 0 means no limit.
type ClientSubscription ¶ added in v0.8.13
type ClientSubscription struct {
// contains filtered or unexported fields
}
ClientSubscription is a subscription established through the Client's Subscribe or EthSubscribe methods.
func (*ClientSubscription) Err ¶ added in v0.8.13
func (sub *ClientSubscription) Err() <-chan error
Err returns the subscription error channel. The intended use of Err is to schedule resubscription when the client connection is closed unexpectedly.
The error channel receives a value when the subscription has ended due to an error. The received error is nil if Close has been called on the underlying client and no other error has occurred.
The error channel is closed when Unsubscribe is called on the subscription.
func (*ClientSubscription) Unsubscribe ¶ added in v0.8.13
func (sub *ClientSubscription) Unsubscribe()
Unsubscribe unsubscribes the notification and closes the error channel. It can safely be called more than once.
type CodecOption
deprecated
added in
v0.8.13
type CodecOption int
CodecOption specifies which type of messages a codec supports.
Deprecated: this option is no longer honored by Server.
const ( // OptionMethodInvocation is an indication that the codec supports RPC method calls OptionMethodInvocation CodecOption = 1 << iota // OptionSubscriptions is an indication that the codec supports RPC notifications OptionSubscriptions = 1 << iota // support pub sub )
type Conn ¶ added in v0.8.13
type Conn interface { io.ReadWriteCloser SetWriteDeadline(time.Time) error }
Conn is a subset of the methods of net.Conn which are sufficient for ServerCodec.
type ConnRemoteAddr ¶ added in v0.8.13
type ConnRemoteAddr interface {
RemoteAddr() string
}
ConnRemoteAddr wraps the RemoteAddr operation, which returns a description of the peer address of a connection. If a Conn also implements ConnRemoteAddr, this description is used in log messages.
type DataError ¶ added in v0.8.13
type DataError interface { Error() string // returns the message ErrorData() interface{} // returns the error data }
A DataError contains some data in addition to the error message.
type Error ¶ added in v0.8.13
Error wraps RPC errors, which contain an error code in addition to the message.
type HTTPAuth ¶ added in v0.12.1
A HTTPAuth function is called by the client whenever a HTTP request is sent. The function must be safe for concurrent use.
Usually, HTTPAuth functions will call h.Set("authorization", "...") to add auth information to the request.
type HTTPError ¶ added in v0.8.13
HTTPError is returned by client operations when the HTTP status code of the response is not a 2xx status.
type HTTPTimeouts ¶ added in v0.8.13
type HTTPTimeouts struct { // ReadTimeout is the maximum duration for reading the entire // request, including the body. // // Because ReadTimeout does not let 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 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 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, ReadHeaderTimeout is used. IdleTimeout time.Duration }
HTTPTimeouts represents the configuration params for the HTTP RPC server.
type ID ¶ added in v0.8.13
type ID string
ID defines a pseudo random number that is used to identify RPC subscriptions.
type Notifier ¶ added in v0.8.13
type Notifier struct {
// contains filtered or unexported fields
}
Notifier is tied to a RPC connection that supports subscriptions. Server callbacks use the notifier to send notifications.
func NotifierFromContext ¶ added in v0.8.13
NotifierFromContext returns the Notifier value stored in ctx, if any.
func (*Notifier) Closed ¶ added in v0.8.13
func (n *Notifier) Closed() <-chan interface{}
Closed returns a channel that is closed when the RPC connection is closed. Deprecated: use subscription error channel
func (*Notifier) CreateSubscription ¶ added in v0.8.13
func (n *Notifier) CreateSubscription() *Subscription
CreateSubscription returns a new subscription that is coupled to the RPC connection. By default subscriptions are inactive and notifications are dropped until the subscription is marked as active. This is done by the RPC server after the subscription ID is send to the client.
type PeerInfo ¶ added in v0.8.13
type PeerInfo struct { // Transport is name of the protocol used by the client. // This can be "http", "ws" or "ipc". Transport string // Address of client. This will usually contain the IP address and port. RemoteAddr string // Additional information for HTTP and WebSocket connections. HTTP struct { // Protocol version, i.e. "HTTP/1.1". This is not set for WebSocket. Version string // Header values sent by the client. UserAgent string Origin string Host string } }
PeerInfo contains information about the remote end of the network connection.
This is available within RPC method handlers through the context. Call PeerInfoFromContext to get information about the client connection related to the current method call.
func PeerInfoFromContext ¶ added in v0.8.13
PeerInfoFromContext returns information about the client's network connection. Use this with the context passed to RPC method handler functions.
The zero value is returned if no connection info is present in ctx.
type RPCService ¶ added in v0.8.13
type RPCService struct {
// contains filtered or unexported fields
}
RPCService gives meta information about the server. e.g. gives information about the loaded modules.
func (*RPCService) Modules ¶ added in v0.8.13
func (s *RPCService) Modules() map[string]string
Modules returns the list of RPC services with their version number
type Server ¶ added in v0.8.13
type Server struct {
// contains filtered or unexported fields
}
Server is an RPC server.
func NewServer ¶ added in v0.8.13
NewServer creates a new server instance with no registered handlers.
If [maximumDuration] > 0, the deadline of incoming requests is [maximumDuration] in the future. Otherwise, no deadline is assigned to incoming requests.
func (*Server) RegisterName ¶ added in v0.8.13
RegisterName creates a service for the given receiver type under the given name. When no methods on the given receiver match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is created and added to the service collection this server provides to clients.
func (*Server) ServeCodec ¶ added in v0.8.13
func (s *Server) ServeCodec(codec ServerCodec, options CodecOption, apiMaxDuration, refillRate, maxStored time.Duration)
ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the response back using the given codec. It will block until the codec is closed or the server is stopped. In either case the codec is closed.
Note that codec options are no longer supported.
func (*Server) ServeHTTP ¶ added in v0.8.13
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves JSON-RPC requests over HTTP.
func (*Server) SetBatchLimits ¶
SetBatchLimits sets limits applied to batch requests. There are two limits: 'itemLimit' is the maximum number of items in a batch. 'maxResponseSize' is the maximum number of response bytes across all requests in a batch.
This method should be called before processing any requests via ServeCodec, ServeHTTP, ServeListener etc.
func (*Server) Stop ¶ added in v0.8.13
func (s *Server) Stop()
Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending requests to finish, then closes all codecs which will cancel pending requests and subscriptions.
func (*Server) WebsocketHandler ¶ added in v0.8.13
WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections.
allowedOrigins should be a comma-separated list of allowed origin URLs. To allow connections with any origin, pass "*".
type ServerCodec ¶ added in v0.8.13
type ServerCodec interface {
// contains filtered or unexported methods
}
ServerCodec implements reading, parsing and writing RPC messages for the server side of a RPC session. Implementations must be go-routine safe since the codec can be called in multiple go-routines concurrently.
func NewCodec ¶ added in v0.8.13
func NewCodec(conn Conn) ServerCodec
NewCodec creates a codec on the given connection. If conn implements ConnRemoteAddr, log messages will use it to include the remote address of the connection.
func NewFuncCodec ¶ added in v0.8.13
func NewFuncCodec(conn deadlineCloser, encode encodeFunc, decode decodeFunc) ServerCodec
NewFuncCodec creates a codec which uses the given functions to read and write. If conn implements ConnRemoteAddr, log messages will use it to include the remote address of the connection.
type Subscription ¶ added in v0.8.13
type Subscription struct { ID ID // contains filtered or unexported fields }
A Subscription is created by a notifier and tied to that notifier. The client can use this subscription to wait for an unsubscribe request for the client, see Err().
func (*Subscription) Err ¶ added in v0.8.13
func (s *Subscription) Err() <-chan error
Err returns a channel that is closed when the client send an unsubscribe request.
func (*Subscription) MarshalJSON ¶ added in v0.8.13
func (s *Subscription) MarshalJSON() ([]byte, error)
MarshalJSON marshals a subscription as its ID.