...

Package jsonrpc2

import "golang.org/x/tools/internal/jsonrpc2"
Overview
Index
Subdirectories

Overview ▾

Package jsonrpc2 is a minimal implementation of the JSON RPC 2 spec. https://www.jsonrpc.org/specification It is intended to be compatible with other implementations at the wire level.

Index ▾

Constants
Variables
func ListenAndServe(ctx context.Context, network, addr string, server StreamServer, idleTimeout time.Duration) error
func MethodNotFound(ctx context.Context, reply Replier, req Request) error
func NewError(code int64, message string) error
func Serve(ctx context.Context, ln net.Listener, server StreamServer, idleTimeout time.Duration) error
type Call
    func NewCall(id ID, method string, params interface{}) (*Call, error)
    func (msg *Call) ID() ID
    func (c *Call) MarshalJSON() ([]byte, error)
    func (msg *Call) Method() string
    func (msg *Call) Params() json.RawMessage
    func (c *Call) UnmarshalJSON(data []byte) error
type Conn
    func NewConn(s Stream) Conn
type Framer
type Handler
    func AsyncHandler(handler Handler) Handler
    func CancelHandler(handler Handler) (Handler, func(id ID))
    func MustReplyHandler(handler Handler) Handler
type ID
    func NewIntID(v int64) ID
    func NewStringID(v string) ID
    func (id ID) Format(f fmt.State, r rune)
    func (id *ID) MarshalJSON() ([]byte, error)
    func (id *ID) UnmarshalJSON(data []byte) error
type Message
    func DecodeMessage(data []byte) (Message, error)
type Notification
    func NewNotification(method string, params interface{}) (*Notification, error)
    func (n *Notification) MarshalJSON() ([]byte, error)
    func (msg *Notification) Method() string
    func (msg *Notification) Params() json.RawMessage
    func (n *Notification) UnmarshalJSON(data []byte) error
type Replier
type Request
type Response
    func NewResponse(id ID, result interface{}, err error) (*Response, error)
    func (msg *Response) Err() error
    func (msg *Response) ID() ID
    func (r *Response) MarshalJSON() ([]byte, error)
    func (msg *Response) Result() json.RawMessage
    func (r *Response) UnmarshalJSON(data []byte) error
type ServerFunc
    func (f ServerFunc) ServeStream(ctx context.Context, c Conn) error
type Stream
    func NewHeaderStream(conn net.Conn) Stream
    func NewRawStream(conn net.Conn) Stream
type StreamServer
    func HandlerServer(h Handler) StreamServer
type WireError
    func (err *WireError) Error() string

Package files

conn.go handler.go jsonrpc2.go labels.go messages.go serve.go stream.go wire.go

Constants

const (
    Inbound  = "in"
    Outbound = "out"
)
const (
    // ErrIdleTimeout is returned when serving timed out waiting for new connections.
    ErrIdleTimeout = constError("timed out waiting for new connections")
)

Variables

These keys are used for creating labels to instrument jsonrpc2 events.

var (
    Method        = keys.NewString("method", "")
    RPCID         = keys.NewString("id", "")
    RPCDirection  = keys.NewString("direction", "")
    Started       = keys.NewInt64("started", "Count of started RPCs.")
    SentBytes     = keys.NewInt64("sent_bytes", "Bytes sent.")         //, unit.Bytes)
    ReceivedBytes = keys.NewInt64("received_bytes", "Bytes received.") //, unit.Bytes)
    StatusCode    = keys.NewString("status.code", "")
    Latency       = keys.NewFloat64("latency_ms", "Elapsed time in milliseconds") //, unit.Milliseconds)
)
var (
    // ErrUnknown should be used for all non coded errors.
    ErrUnknown = NewError(-32001, "JSON RPC unknown error")
    // ErrParse is used when invalid JSON was received by the server.
    ErrParse = NewError(-32700, "JSON RPC parse error")
    //ErrInvalidRequest is used when the JSON sent is not a valid Request object.
    ErrInvalidRequest = NewError(-32600, "JSON RPC invalid request")
    // ErrMethodNotFound should be returned by the handler when the method does
    // not exist / is not available.
    ErrMethodNotFound = NewError(-32601, "JSON RPC method not found")
    // ErrInvalidParams should be returned by the handler when method
    // parameter(s) were invalid.
    ErrInvalidParams = NewError(-32602, "JSON RPC invalid params")
    // ErrInternal is not currently returned but defined for completeness.
    ErrInternal = NewError(-32603, "JSON RPC internal error")

    //ErrServerOverloaded is returned when a message was refused due to a
    //server being temporarily unable to accept any new messages.
    ErrServerOverloaded = NewError(-32000, "JSON RPC overloaded")
)

func ListenAndServe

func ListenAndServe(ctx context.Context, network, addr string, server StreamServer, idleTimeout time.Duration) error

ListenAndServe starts an jsonrpc2 server on the given address. If idleTimeout is non-zero, ListenAndServe exits after there are no clients for this duration, otherwise it exits only on error.

func MethodNotFound

func MethodNotFound(ctx context.Context, reply Replier, req Request) error

MethodNotFound is a Handler that replies to all call requests with the standard method not found response. This should normally be the final handler in a chain.

func NewError

func NewError(code int64, message string) error

func Serve

func Serve(ctx context.Context, ln net.Listener, server StreamServer, idleTimeout time.Duration) error

Serve accepts incoming connections from the network, and handles them using the provided server. If idleTimeout is non-zero, ListenAndServe exits after there are no clients for this duration, otherwise it exits only on error.

type Call

Call is a request that expects a response. The response will have a matching ID.

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

func NewCall

func NewCall(id ID, method string, params interface{}) (*Call, error)

NewCall constructs a new Call message for the supplied ID, method and parameters.

func (*Call) ID

func (msg *Call) ID() ID

func (*Call) MarshalJSON

func (c *Call) MarshalJSON() ([]byte, error)

func (*Call) Method

func (msg *Call) Method() string

func (*Call) Params

func (msg *Call) Params() json.RawMessage

func (*Call) UnmarshalJSON

func (c *Call) UnmarshalJSON(data []byte) error

type Conn

Conn is the common interface to jsonrpc clients and servers. Conn is bidirectional; it does not have a designated server or client end. It manages the jsonrpc2 protocol, connecting responses back to their calls.

type Conn interface {
    // Call invokes the target method and waits for a response.
    // The params will be marshaled to JSON before sending over the wire, and will
    // be handed to the method invoked.
    // The response will be unmarshaled from JSON into the result.
    // The id returned will be unique from this connection, and can be used for
    // logging or tracking.
    Call(ctx context.Context, method string, params, result interface{}) (ID, error)

    // Notify invokes the target method but does not wait for a response.
    // The params will be marshaled to JSON before sending over the wire, and will
    // be handed to the method invoked.
    Notify(ctx context.Context, method string, params interface{}) error

    // Go starts a goroutine to handle the connection.
    // It must be called exactly once for each Conn.
    // It returns immediately.
    // You must block on Done() to wait for the connection to shut down.
    // This is a temporary measure, this should be started automatically in the
    // future.
    Go(ctx context.Context, handler Handler)

    // Close closes the connection and it's underlying stream.
    // It does not wait for the close to complete, use the Done() channel for
    // that.
    Close() error

    // Done returns a channel that will be closed when the processing goroutine
    // has terminated, which will happen if Close() is called or an underlying
    // stream is closed.
    Done() <-chan struct{}

    // Err returns an error if there was one from within the processing goroutine.
    // If err returns non nil, the connection will be already closed or closing.
    Err() error
}

func NewConn

func NewConn(s Stream) Conn

NewConn creates a new connection object around the supplied stream.

type Framer

Framer wraps a network connection up into a Stream. It is responsible for the framing and encoding of messages into wire form. NewRawStream and NewHeaderStream are implementations of a Framer.

type Framer func(conn net.Conn) Stream

type Handler

Handler is invoked to handle incoming requests. The Replier sends a reply to the request and must be called exactly once.

type Handler func(ctx context.Context, reply Replier, req Request) error

func AsyncHandler

func AsyncHandler(handler Handler) Handler

AsyncHandler returns a handler that processes each request goes in its own goroutine. The handler returns immediately, without the request being processed. Each request then waits for the previous request to finish before it starts. This allows the stream to unblock at the cost of unbounded goroutines all stalled on the previous one.

func CancelHandler

func CancelHandler(handler Handler) (Handler, func(id ID))

CancelHandler returns a handler that supports cancellation, and a function that can be used to trigger canceling in progress requests.

func MustReplyHandler

func MustReplyHandler(handler Handler) Handler

MustReplyHandler creates a Handler that panics if the wrapped handler does not call Reply for every request that it is passed.

type ID

ID is a Request identifier.

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

func NewIntID

func NewIntID(v int64) ID

NewIntID returns a new numerical request ID.

func NewStringID

func NewStringID(v string) ID

NewStringID returns a new string request ID.

func (ID) Format

func (id ID) Format(f fmt.State, r rune)

Format writes the ID to the formatter. If the rune is q the representation is non ambiguous, string forms are quoted, number forms are preceded by a #

func (*ID) MarshalJSON

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

func (*ID) UnmarshalJSON

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

type Message

Message is the interface to all jsonrpc2 message types. They share no common functionality, but are a closed set of concrete types that are allowed to implement this interface. The message types are *Call, *Notification and *Response.

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

func DecodeMessage

func DecodeMessage(data []byte) (Message, error)

type Notification

Notification is a request for which a response cannot occur, and as such it has not ID.

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

func NewNotification

func NewNotification(method string, params interface{}) (*Notification, error)

NewNotification constructs a new Notification message for the supplied method and parameters.

func (*Notification) MarshalJSON

func (n *Notification) MarshalJSON() ([]byte, error)

func (*Notification) Method

func (msg *Notification) Method() string

func (*Notification) Params

func (msg *Notification) Params() json.RawMessage

func (*Notification) UnmarshalJSON

func (n *Notification) UnmarshalJSON(data []byte) error

type Replier

Replier is passed to handlers to allow them to reply to the request. If err is set then result will be ignored.

type Replier func(ctx context.Context, result interface{}, err error) error

type Request

Request is the shared interface to jsonrpc2 messages that request a method be invoked. The request types are a closed set of *Call and *Notification.

type Request interface {
    Message
    // Method is a string containing the method name to invoke.
    Method() string
    // Params is an JSON value (object, array, null, or "") with the parameters of the method.
    Params() json.RawMessage
    // contains filtered or unexported methods
}

type Response

Response is a reply to a Call. It will have the same ID as the call it is a response to.

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

func NewResponse

func NewResponse(id ID, result interface{}, err error) (*Response, error)

NewResponse constructs a new Response message that is a reply to the supplied. If err is set result may be ignored.

func (*Response) Err

func (msg *Response) Err() error

func (*Response) ID

func (msg *Response) ID() ID

func (*Response) MarshalJSON

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

func (*Response) Result

func (msg *Response) Result() json.RawMessage

func (*Response) UnmarshalJSON

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

type ServerFunc

The ServerFunc type is an adapter that implements the StreamServer interface using an ordinary function.

type ServerFunc func(context.Context, Conn) error

func (ServerFunc) ServeStream

func (f ServerFunc) ServeStream(ctx context.Context, c Conn) error

ServeStream calls f(ctx, s).

type Stream

Stream abstracts the transport mechanics from the JSON RPC protocol. A Conn reads and writes messages using the stream it was provided on construction, and assumes that each call to Read or Write fully transfers a single message, or returns an error. A stream is not safe for concurrent use, it is expected it will be used by a single Conn in a safe manner.

type Stream interface {
    // Read gets the next message from the stream.
    Read(context.Context) (Message, int64, error)
    // Write sends a message to the stream.
    Write(context.Context, Message) (int64, error)
    // Close closes the connection.
    // Any blocked Read or Write operations will be unblocked and return errors.
    Close() error
}

func NewHeaderStream

func NewHeaderStream(conn net.Conn) Stream

NewHeaderStream returns a Stream built on top of a net.Conn. The messages are sent with HTTP content length and MIME type headers. This is the format used by LSP and others.

func NewRawStream

func NewRawStream(conn net.Conn) Stream

NewRawStream returns a Stream built on top of a net.Conn. The messages are sent with no wrapping, and rely on json decode consistency to determine message boundaries.

type StreamServer

A StreamServer is used to serve incoming jsonrpc2 clients communicating over a newly created connection.

type StreamServer interface {
    ServeStream(context.Context, Conn) error
}

func HandlerServer

func HandlerServer(h Handler) StreamServer

HandlerServer returns a StreamServer that handles incoming streams using the provided handler.

type WireError

WireError represents a structured error in a Response.

type WireError struct {
    // Code is an error code indicating the type of failure.
    Code int64 `json:"code"`
    // Message is a short description of the error.
    Message string `json:"message"`
    // Data is optional structured data containing additional information about the error.
    Data *json.RawMessage `json:"data,omitempty"`
}

func (*WireError) Error

func (err *WireError) Error() string

Subdirectories

Name Synopsis
..