jsonrpc2: github.com/sourcegraph/jsonrpc2 Index | Files | Directories

package jsonrpc2

import "github.com/sourcegraph/jsonrpc2"

Package jsonrpc2 provides a client and server implementation of [JSON-RPC 2.0](http://www.jsonrpc.org/specification).

Index

Package Files

async.go call_opt.go conn_opt.go handler_with_error.go jsonrpc2.go stream.go

Constants

const (
    CodeParseError     = -32700
    CodeInvalidRequest = -32600
    CodeMethodNotFound = -32601
    CodeInvalidParams  = -32602
    CodeInternalError  = -32603
)

Errors defined in the JSON-RPC spec. See http://www.jsonrpc.org/specification#error_object.

Variables

var ErrClosed = errors.New("jsonrpc2: connection is closed")

ErrClosed indicates that the JSON-RPC connection is closed (or in the process of closing).

type CallOption Uses

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

CallOption is an option that can be provided to (*Conn).Call to configure custom behavior. See Meta.

func Meta Uses

func Meta(meta interface{}) CallOption

Meta returns a call option which attaches the given meta object to the JSON-RPC 2.0 request (this is a Sourcegraph extension to JSON RPC 2.0 for carrying metadata).

func PickID Uses

func PickID(id ID) CallOption

PickID returns a call option which sets the ID on a request. Care must be taken to ensure there are no conflicts with any previously picked ID, nor with the default sequence ID.

type Conn Uses

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

Conn is a JSON-RPC client/server connection. The JSON-RPC protocol is symmetric, so a Conn runs on both ends of a client-server connection.

func NewConn Uses

func NewConn(ctx context.Context, stream ObjectStream, h Handler, opts ...ConnOpt) *Conn

NewConn creates a new JSON-RPC client/server connection using the given ReadWriteCloser (typically a TCP connection or stdio). The JSON-RPC protocol is symmetric, so a Conn runs on both ends of a client-server connection.

NewClient consumes conn, so you should call Close on the returned client not on the given conn.

func (*Conn) Call Uses

func (c *Conn) Call(ctx context.Context, method string, params, result interface{}, opts ...CallOption) error

Call initiates a JSON-RPC call using the specified method and params, and waits for the response. If the response is successful, its result is stored in result (a pointer to a value that can be JSON-unmarshaled into); otherwise, a non-nil error is returned.

func (*Conn) Close Uses

func (c *Conn) Close() error

Close closes the JSON-RPC connection. The connection may not be used after it has been closed.

func (*Conn) DisconnectNotify Uses

func (c *Conn) DisconnectNotify() <-chan struct{}

DisconnectNotify returns a channel that is closed when the underlying connection is disconnected.

func (*Conn) Notify Uses

func (c *Conn) Notify(ctx context.Context, method string, params interface{}, opts ...CallOption) error

Notify is like Call, but it returns when the notification request is sent (without waiting for a response, because JSON-RPC notifications do not have responses).

func (*Conn) Reply Uses

func (c *Conn) Reply(ctx context.Context, id ID, result interface{}) error

Reply sends a successful response with a result.

func (*Conn) ReplyWithError Uses

func (c *Conn) ReplyWithError(ctx context.Context, id ID, respErr *Error) error

ReplyWithError sends a response with an error.

func (*Conn) SendResponse Uses

func (c *Conn) SendResponse(ctx context.Context, resp *Response) error

SendResponse sends resp to the peer. It is lower level than (*Conn).Reply.

type ConnOpt Uses

type ConnOpt func(*Conn)

ConnOpt is the type of function that can be passed to NewConn to customize the Conn before it is created.

func LogMessages Uses

func LogMessages(logger Logger) ConnOpt

LogMessages causes all messages sent and received on conn to be logged using the provided logger.

func OnRecv Uses

func OnRecv(f func(*Request, *Response)) ConnOpt

OnRecv causes all requests received on conn to invoke f(req, nil) and all responses to invoke f(req, resp),

func OnSend Uses

func OnSend(f func(*Request, *Response)) ConnOpt

OnSend causes all requests sent on conn to invoke f(req, nil) and all responses to invoke f(nil, resp),

type Error Uses

type Error struct {
    Code    int64            `json:"code"`
    Message string           `json:"message"`
    Data    *json.RawMessage `json:"data"`
}

Error represents a JSON-RPC response error.

func (*Error) Error Uses

func (e *Error) Error() string

Error implements the Go error interface.

func (*Error) SetError Uses

func (e *Error) SetError(v interface{})

SetError sets e.Error to the JSON representation of v. If JSON marshaling fails, it panics.

type Handler Uses

type Handler interface {
    // Handle is called to handle a request. No other requests are handled
    // until it returns. If you do not require strict ordering behavior
    // of received RPCs, it is suggested to wrap your handler in
    // AsyncHandler.
    Handle(context.Context, *Conn, *Request)
}

Handler handles JSON-RPC requests and notifications.

func AsyncHandler Uses

func AsyncHandler(h Handler) Handler

AsyncHandler wraps a Handler such that each request is handled in its own goroutine. It is a convenience wrapper.

type HandlerWithErrorConfigurer Uses

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

HandlerWithErrorConfigurer is a handler created by HandlerWithError.

func HandlerWithError Uses

func HandlerWithError(handleFunc func(context.Context, *Conn, *Request) (result interface{}, err error)) *HandlerWithErrorConfigurer

HandlerWithError implements Handler by calling the func for each request and handling returned errors and results.

func (*HandlerWithErrorConfigurer) Handle Uses

func (h *HandlerWithErrorConfigurer) Handle(ctx context.Context, conn *Conn, req *Request)

Handle implements Handler.

func (*HandlerWithErrorConfigurer) SuppressErrClosed Uses

func (h *HandlerWithErrorConfigurer) SuppressErrClosed() Handler

SuppressErrClosed makes the handler suppress jsonrpc2.ErrClosed errors from being logged. The original handler `h` is returned.

This is optional because only in some cases is this behavior desired. For example, a handler that serves end-user connections may not want to log ErrClosed because it just indicates the end-user connection has gone away for any reason (they could have lost wifi connection, are no longer interested in the request and closed the connection, etc) and as such it would be log spam, whereas a handler that serves internal connections would never expect connections to go away unexpectedly (which could indicate service degradation, etc) and as such ErrClosed should always be logged.

type ID Uses

type ID struct {
    // At most one of Num or Str may be nonzero. If both are zero
    // valued, then IsNum specifies which field's value is to be used
    // as the ID.
    Num uint64
    Str string

    // IsString controls whether the Num or Str field's value should be
    // used as the ID, when both are zero valued. It must always be
    // set to true if the request ID is a string.
    IsString bool
}

ID represents a JSON-RPC 2.0 request ID, which may be either a string or number (or null, which is unsupported).

func (ID) MarshalJSON Uses

func (id ID) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (ID) String Uses

func (id ID) String() string

func (*ID) UnmarshalJSON Uses

func (id *ID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type JSONRPC2 Uses

type JSONRPC2 interface {
    // Call issues a standard request (http://www.jsonrpc.org/specification#request_object).
    Call(ctx context.Context, method string, params, result interface{}, opt ...CallOption) error

    // Notify issues a notification request (http://www.jsonrpc.org/specification#notification).
    Notify(ctx context.Context, method string, params interface{}, opt ...CallOption) error

    // Close closes the underlying connection, if it exists.
    Close() error
}

JSONRPC2 describes an interface for issuing requests that speak the JSON-RPC 2 protocol. It isn't really necessary for this package itself, but is useful for external users that use the interface as an API boundary.

type Logger Uses

type Logger interface {
    Printf(format string, v ...interface{})
}

Logger interface implements one method - Printf. You can use the stdlib logger *log.Logger

type ObjectCodec Uses

type ObjectCodec interface {
    // WriteObject writes a JSON-RPC 2.0 object to the stream.
    WriteObject(stream io.Writer, obj interface{}) error

    // ReadObject reads the next JSON-RPC 2.0 object from the stream
    // and stores it in the value pointed to by v.
    ReadObject(stream *bufio.Reader, v interface{}) error
}

An ObjectCodec specifies how to encoed and decode a JSON-RPC 2.0 object in a stream.

type ObjectStream Uses

type ObjectStream interface {
    // WriteObject writes a JSON-RPC 2.0 object to the stream.
    WriteObject(obj interface{}) error

    // ReadObject reads the next JSON-RPC 2.0 object from the stream
    // and stores it in the value pointed to by v.
    ReadObject(v interface{}) error

    io.Closer
}

An ObjectStream is a bidirectional stream of JSON-RPC 2.0 objects.

func NewBufferedStream Uses

func NewBufferedStream(conn io.ReadWriteCloser, codec ObjectCodec) ObjectStream

NewBufferedStream creates a buffered stream from a network connection (or other similar interface). The underlying objectStream is used to produce the bytes to write to the stream for the JSON-RPC 2.0 objects.

type Request Uses

type Request struct {
    Method string           `json:"method"`
    Params *json.RawMessage `json:"params,omitempty"`
    ID     ID               `json:"id"`
    Notif  bool             `json:"-"`

    // Meta optionally provides metadata to include in the request.
    //
    // NOTE: It is not part of spec. However, it is useful for propogating
    // tracing context, etc.
    Meta *json.RawMessage `json:"meta,omitempty"`
}

Request represents a JSON-RPC request or notification. See http://www.jsonrpc.org/specification#request_object and http://www.jsonrpc.org/specification#notification.

func (Request) MarshalJSON Uses

func (r Request) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0" property.

func (*Request) SetMeta Uses

func (r *Request) SetMeta(v interface{}) error

SetMeta sets r.Meta to the JSON representation of v. If JSON marshaling fails, it returns an error.

func (*Request) SetParams Uses

func (r *Request) SetParams(v interface{}) error

SetParams sets r.Params to the JSON representation of v. If JSON marshaling fails, it returns an error.

func (*Request) UnmarshalJSON Uses

func (r *Request) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Response Uses

type Response struct {
    ID     ID               `json:"id"`
    Result *json.RawMessage `json:"result,omitempty"`
    Error  *Error           `json:"error,omitempty"`

    // Meta optionally provides metadata to include in the response.
    //
    // NOTE: It is not part of spec. However, it is useful for propogating
    // tracing context, etc.
    Meta *json.RawMessage `json:"meta,omitempty"`
}

Response represents a JSON-RPC response. See http://www.jsonrpc.org/specification#response_object.

func (Response) MarshalJSON Uses

func (r Response) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0" property.

func (*Response) SetResult Uses

func (r *Response) SetResult(v interface{}) error

SetResult sets r.Result to the JSON representation of v. If JSON marshaling fails, it returns an error.

func (*Response) UnmarshalJSON Uses

func (r *Response) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type VSCodeObjectCodec Uses

type VSCodeObjectCodec struct{}

VSCodeObjectCodec reads/writes JSON-RPC 2.0 objects with Content-Length and Content-Type headers, as specified by https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md#base-protocol.

func (VSCodeObjectCodec) ReadObject Uses

func (VSCodeObjectCodec) ReadObject(stream *bufio.Reader, v interface{}) error

ReadObject implements ObjectCodec.

func (VSCodeObjectCodec) WriteObject Uses

func (VSCodeObjectCodec) WriteObject(stream io.Writer, obj interface{}) error

WriteObject implements ObjectCodec.

type VarintObjectCodec Uses

type VarintObjectCodec struct{}

VarintObjectCodec reads/writes JSON-RPC 2.0 objects with a varint header that encodes the byte length.

func (VarintObjectCodec) ReadObject Uses

func (VarintObjectCodec) ReadObject(stream *bufio.Reader, v interface{}) error

ReadObject implements ObjectCodec.

func (VarintObjectCodec) WriteObject Uses

func (VarintObjectCodec) WriteObject(stream io.Writer, obj interface{}) error

WriteObject implements ObjectCodec.

Directories

PathSynopsis
websocketPackage websocket provides WebSocket transport support for JSON-RPC 2.0.

Package jsonrpc2 imports 13 packages (graph) and is imported by 40 packages. Updated 2019-11-05. Refresh now. Tools for package owners.