jsonrpc2

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

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

Go to latest
Published: Aug 10, 2025 License: MIT Imports: 13 Imported by: 2

README

jsonrpc2

Build Status License

alis-is/jsonrpc2 is library to simplify implementation of JSON-RPC2.0 services. Support batch requests and generics of params and results.

Inspired by/forked from teambition/jsonrpc-go and sourcegraph/jsonrpc2

Installation

go get github.com/alis-is/jsonrpc2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInternalInvalidJsonRpcMessage   = errors.New("invalid jsonrpc 2.0 message")
	ErrInternalNotRequest              = errors.New("not a request")
	ErrInternalMethodRequired          = errors.New("method is required")
	ErrInternalInvalidMessageStructure = errors.New("invalid message structure")
	ErrInternalUnsupportedMessageKind  = errors.New("unsupported message kind")
	ErrEmptyResponse                   = errors.New("empty response")
)
View Source
var (
	ErrInvalidEndpoint = errors.New("invalid endpoint")
	ErrStreamClosed    = errors.New("stream closed")
)

Functions

func BatchTo

func BatchTo[TParams Params, TResult Result](ctx context.Context, c EndpointClient, requests []RequestInfo[TParams], results []*Response[TResult]) error

func MessageToErrorResponse

func MessageToErrorResponse(rpc *message) (*errorResponse, error)

func MessageToRequest

func MessageToRequest[TParam Params](r *message) *request[TParam]

func MessageToSuccessResponse

func MessageToSuccessResponse[TResult Result](rpc *message) (*successResponse[TResult], error)

func NewErrorResponse

func NewErrorResponse[TId Id](id TId, err *ErrorObj) *errorResponse

func NewErrorResponseI

func NewErrorResponseI(id interface{}, err *ErrorObj) *errorResponse

func NewNotification

func NewNotification[TParam Params](method string, params TParam) (req *request[TParam])

func NewRequest

func NewRequest[TId Id, TParam Params](id TId, method string, params TParam) (req *request[TParam])

func NewSuccessResponse

func NewSuccessResponse[TId Id, TResult Result](id TId, result TResult) *successResponse[TResult]

func NewSuccessResponseI

func NewSuccessResponseI[TResult Result](id interface{}, result TResult) *successResponse[TResult]

func Notify

func Notify[TParams Params](ctx context.Context, c EndpointClient, method string, params TParams) error

notify

func ProcessRpcRequest

func ProcessRpcRequest(ctx context.Context, reg RpcMethodRegistry, rpcMsg *message) interface{}

func RegisterEndpointMethod

func RegisterEndpointMethod[TParam Params, TResult Result](c EndpointServer, method string, handler RpcMethod[TParam, TResult])

register method to server endpoint

func RegisterMethod

func RegisterMethod[TParam Params, TResult Result](reg RpcMethodRegistry, method string, handler RpcMethod[TParam, TResult])

func RegisterServerMuxEndpointMethod

func RegisterServerMuxEndpointMethod[TParam Params, TResult Result](mux *ServerMux, endpoint string, method string, handler RpcMethod[TParam, TResult])

func RequestTo

func RequestTo[TParams Params, TResult Result](ctx context.Context, c EndpointClient, method string, params TParams, result *Response[TResult]) error

func ResponseFromError

func ResponseFromError[TId Id](id TId, err *Error) *errorResponse

Types

type EndpointClient

type EndpointClient interface {
	WriteObject(obj interface{}) error
	RegisterPendingRequest(id interface{}) <-chan message
	UnregisterPendingRequest(id interface{})
	Close() error
	IsClosed() bool
	UseLogger(logger *slog.Logger)
}

type EndpointRegistry

type EndpointRegistry map[string]RpcMethodRegistry

type EndpointServer

type EndpointServer interface {
	GetMethods() RpcMethodRegistry
	UseLogger(logger *slog.Logger)
}

type Error

type Error struct {
	Kind ErrorKind
	Data interface{}
	// contains filtered or unexported fields
}

func NewInternalError

func NewInternalError() *Error

func NewInternalErrorWithData

func NewInternalErrorWithData[T any](data T) *Error

func NewInvalidParams

func NewInvalidParams() *Error

func NewInvalidParamsWithData

func NewInvalidParamsWithData[T any](data T) *Error

func NewInvalidRequest

func NewInvalidRequest() *Error

func NewInvalidRequestWithData

func NewInvalidRequestWithData[T any](data T) *Error

func NewMethodNotFound

func NewMethodNotFound() *Error

func NewMethodNotFoundWithData

func NewMethodNotFoundWithData[T any](data T) *Error

func NewParseError

func NewParseError() *Error

func NewParseErrorWithData

func NewParseErrorWithData[T any](data T) *Error

func NewServerError

func NewServerError(code int) *Error

code has to be in range -32099 to -32000

func NewServerErrorWithData

func NewServerErrorWithData[T any](code int, data T) *Error

func NewUnknownError

func NewUnknownError() *Error

func NewUnknownErrorWithData

func NewUnknownErrorWithData[T any](data T) *Error

func (*Error) Error

func (e *Error) Error() string

func (*Error) ToHttpError

func (e *Error) ToHttpError() int

func (*Error) ToResponse

func (e *Error) ToResponse(id interface{}) *errorResponse

func (*Error) ToResponseBytes

func (e *Error) ToResponseBytes(id interface{}) []byte

type ErrorKind

type ErrorKind string
const (
	ParseErrorKind     ErrorKind = "Parse error"
	InvalidRequestKind ErrorKind = "Invalid Request"
	MethodNotFoundKind ErrorKind = "Method not found"
	InvalidParamsKind  ErrorKind = "Invalid params"
	InternalErrorKind  ErrorKind = "Internal error"
	UnknownErrorKind   ErrorKind = "Unknown error"
	ServerErrorKind    ErrorKind = "Server error"
)

type ErrorObj

type ErrorObj struct {
	Code    int              `json:"code"`
	Message string           `json:"message"`
	Data    *json.RawMessage `json:"data,omitempty"`
}

func (*ErrorObj) ToErrorResponse

func (e *ErrorObj) ToErrorResponse(id interface{}) *errorResponse

func (*ErrorObj) ToErrorResponseBytes

func (e *ErrorObj) ToErrorResponseBytes(id interface{}) []byte

func (*ErrorObj) ToResponse

func (e *ErrorObj) ToResponse(id interface{}) *Response[interface{}]

type HttpClientEndpoint

type HttpClientEndpoint struct {
	*http.Client
	// contains filtered or unexported fields
}

func NewHttpClientEndpoint

func NewHttpClientEndpoint(baseUrl string, client *http.Client) *HttpClientEndpoint

func (*HttpClientEndpoint) Close

func (c *HttpClientEndpoint) Close() error

func (*HttpClientEndpoint) IsClosed

func (c *HttpClientEndpoint) IsClosed() bool

func (*HttpClientEndpoint) RegisterPendingRequest

func (c *HttpClientEndpoint) RegisterPendingRequest(requestID interface{}) <-chan message

func (*HttpClientEndpoint) UnregisterPendingRequest

func (c *HttpClientEndpoint) UnregisterPendingRequest(requestID interface{})

func (*HttpClientEndpoint) UseLogger

func (c *HttpClientEndpoint) UseLogger(logger *slog.Logger)

func (*HttpClientEndpoint) WriteObject

func (c *HttpClientEndpoint) WriteObject(object interface{}) error

type Id

type Id interface {
	~string | ~int64 | ~int32 | ~int16 | ~int8 | ~int | ~uint64 | ~uint32 | ~uint16 | ~uint8 | ~uint
}

type MessageKind

type MessageKind string
const (
	INVALID_KIND          MessageKind = "invalid"
	NOTIFICATION_KIND     MessageKind = "notification"
	REQUEST_KIND          MessageKind = "request"
	ERROR_RESPONSE_KIND   MessageKind = "error"
	SUCCESS_RESPONSE_KIND MessageKind = "success"
)

type Object

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

Object is a wrapper for a single or batch of rpc messages

func (*Object) GetMessages

func (r *Object) GetMessages() []message

func (*Object) GetSingleMessage

func (r *Object) GetSingleMessage() *message

func (*Object) IsBatch

func (r *Object) IsBatch() bool

func (*Object) MarshalJSON

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

func (*Object) UnmarshalJSON

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

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 encode 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.

func NewPlainObjectStream

func NewPlainObjectStream(conn io.ReadWriteCloser) ObjectStream

NewPlainObjectStream creates a buffered stream from a network connection (or other similar interface). The underlying objectStream produces plain JSON-RPC 2.0 objects without a header.

type Params

type Params interface {
	any | []any
}

type PlainObjectCodec deprecated

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

PlainObjectCodec reads/writes plain JSON-RPC 2.0 objects without a header.

Deprecated: use NewPlainObjectStream

func (PlainObjectCodec) ReadObject

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

ReadObject implements ObjectCodec.

func (PlainObjectCodec) WriteObject

func (c PlainObjectCodec) WriteObject(stream io.Writer, v interface{}) error

WriteObject implements ObjectCodec.

type RequestInfo

type RequestInfo[TParams Params] struct {
	Method         string
	Params         TParams
	IsNotification bool
}

type Response

type Response[TResult Result] struct {
	Id     interface{} `json:"id"`
	Result TResult     `json:"result,omitempty"`
	Error  *ErrorObj   `json:"error,omitempty"`
	// contains filtered or unexported fields
}

func Batch

func Batch[TParams Params, TResult Result](ctx context.Context, c EndpointClient, requests []RequestInfo[TParams]) ([]*Response[TResult], error)

Batch

func MessageToResponse

func MessageToResponse[TResult Result](rpc *message) (*Response[TResult], error)

func NewResponse

func NewResponse[TResult Result](id interface{}, result TResult, err *ErrorObj) *Response[TResult]

func NewResponseI

func NewResponseI[TResult Result](id interface{}, result TResult, err *ErrorObj) *Response[TResult]

func Request

func Request[TParams Params, TResult Result](ctx context.Context, c EndpointClient, method string, params TParams) (*Response[TResult], error)

request

func (*Response[TResult]) IsError

func (r *Response[TResult]) IsError() bool

func (*Response[TResult]) IsSuccess

func (r *Response[TResult]) IsSuccess() bool

func (*Response[TResult]) Unwrap

func (r *Response[TResult]) Unwrap() (TResult, error)

type Result

type Result interface{ any }

type RpcHandler

type RpcHandler func(ctx context.Context, rpcMessage *message) interface{}

type RpcMethod

type RpcMethod[TParam Params, TResult Result] func(ctx context.Context, p TParam) (TResult, *Error)

type RpcMethodRegistry

type RpcMethodRegistry map[string]RpcHandler

func NewMethodRegistry

func NewMethodRegistry() RpcMethodRegistry

type ServerMux

type ServerMux struct {
	http.ServeMux
	// contains filtered or unexported fields
}

func NewServerMux

func NewServerMux() *ServerMux

func (*ServerMux) GetEndpoints

func (mux *ServerMux) GetEndpoints() EndpointRegistry

func (*ServerMux) GetMethods

func (mux *ServerMux) GetMethods() RpcMethodRegistry

func (*ServerMux) RegisterEndpoint

func (mux *ServerMux) RegisterEndpoint(path string)

func (*ServerMux) UseLogger

func (mux *ServerMux) UseLogger(logger *slog.Logger)

type StreamEndpoint

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

StreamEndpoint is a endpoint that implements both client and server side of jsonrpc over a stream. Usually used over tcp or stdio streams.

func NewStreamEndpoint

func NewStreamEndpoint(ctx context.Context, stream ObjectStream) *StreamEndpoint

func (*StreamEndpoint) Close

func (c *StreamEndpoint) Close() error

func (*StreamEndpoint) GetMethods

func (c *StreamEndpoint) GetMethods() RpcMethodRegistry

func (*StreamEndpoint) GetOnCloseListener

func (c *StreamEndpoint) GetOnCloseListener() <-chan struct{}

returns a channel that will be closed when the connection is closed

func (*StreamEndpoint) IsClosed

func (c *StreamEndpoint) IsClosed() bool

func (*StreamEndpoint) ListMethods

func (c *StreamEndpoint) ListMethods() []string

func (*StreamEndpoint) RegisterPendingRequest

func (c *StreamEndpoint) RegisterPendingRequest(requestId interface{}) <-chan message

func (*StreamEndpoint) UnregisterPendingRequest

func (c *StreamEndpoint) UnregisterPendingRequest(requestId interface{})

func (*StreamEndpoint) UseLogger

func (c *StreamEndpoint) UseLogger(logger *slog.Logger)

func (*StreamEndpoint) WriteObject

func (c *StreamEndpoint) WriteObject(obj interface{}) error

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

Jump to

Keyboard shortcuts

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