jsonrpc2

package module
v0.0.0-...-dbf2088 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2018 License: MIT Imports: 12 Imported by: 0

README

jsonrpc2: JSON-RPC 2.0 implementation for Go Build Status Sourcegraph

Package jsonrpc2 provides a Go implementation of JSON-RPC 2.0.

This package is experimental until further notice.

Open the code in Sourcegraph

Known issues

  • Batch requests and responses are not yet supported.

Documentation

Overview

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

Index

Constants

View Source
const (
	// Errors defined in the JSON-RPC spec. See
	// http://www.jsonrpc.org/specification#error_object.
	CodeParseError     = -32700
	CodeInvalidRequest = -32600
	CodeMethodNotFound = -32601
	CodeInvalidParams  = -32602
	CodeInternalError  = -32603
)

Variables

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

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

Functions

This section is empty.

Types

type CallOption

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

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

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

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

func NewConn(ctx context.Context, stream ObjectStream, h Handler, opt ...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

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

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

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

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

func (*Conn) Notify

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

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

Reply sends a successful response with a result.

func (*Conn) ReplyWithError

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

ReplyWithError sends a response with an error.

func (*Conn) SendResponse

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

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

func LogMessages(log *log.Logger) ConnOpt

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

func OnRecv

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

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

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

func (e *Error) Error() string

Error implements the Go error interface.

func (*Error) SetError

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

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

type Handler

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 behaviour
	// 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

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

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

func HandlerWithError

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

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

Handle implements Handler.

func (*HandlerWithErrorConfigurer) SuppressErrClosed

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

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

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

MarshalJSON implements json.Marshaler.

func (ID) String

func (id ID) String() string

func (*ID) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

type JSONRPC2

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 ObjectCodec

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

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

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

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

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

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

func (*Request) SetMeta

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

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

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

UnmarshalJSON implements json.Unmarshaler.

type Response

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

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

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

func (*Response) SetResult

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

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

UnmarshalJSON implements json.Unmarshaler.

type VSCodeObjectCodec

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

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

ReadObject implements ObjectCodec.

func (VSCodeObjectCodec) WriteObject

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

WriteObject implements ObjectCodec.

type VarintObjectCodec

type VarintObjectCodec struct{}

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

func (VarintObjectCodec) ReadObject

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

ReadObject implements ObjectCodec.

func (VarintObjectCodec) WriteObject

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

WriteObject implements ObjectCodec.

Directories

Path Synopsis
Package websocket provides WebSocket transport support for JSON-RPC 2.0.
Package websocket provides WebSocket transport support for JSON-RPC 2.0.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL