jsonrpc

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

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

Go to latest
Published: Oct 11, 2017 License: MIT Imports: 10 Imported by: 0

README

Go kit JSON-RPC transport

Build Status GoDoc Coverage Status Go Report Card

Address issue https://github.com/go-kit/kit/issues/575. Inspired/based on https://github.com/go-kit/kit/pull/576 and https://github.com/go-kit/kit/pull/451

Development

task qa
Dependencies
  • task runner go get github.com/go-task/task

Documentation

Overview

Package jsonrpc provides a JSON RPC (v2.0) binding for endpoints See http://www.jsonrpc.org/specification

Index

Constants

View Source
const (
	// ParseError defines invalid JSON was received by the server.
	// An error occurred on the server while parsing the JSON text.
	ParseError int = -32700

	// InvalidRequestError defines the JSON sent is not a valid Request object.
	InvalidRequestError int = -32600

	// MethodNotFoundError defines the method does not exist / is not available.
	MethodNotFoundError int = -32601

	// InvalidParamsError defines invalid method parameter(s).
	InvalidParamsError int = -32602

	// InternalError defines a server error
	InternalError int = -32603
)
View Source
const (
	// Version defines the version of the JSON RPC implementation
	Version string = "2.0"

	// ContentType defines the content type to be served.
	ContentType string = "application/json; charset=utf-8"
)
View Source
const (
	// ContextKeyRequestJSONRPC is populated in the context by PopulateRequestContext
	ContextKeyRequestJSONRPC contextKey = iota

	// ContextKeyRequestMethod is populated in the context by PopulateRequestContext
	ContextKeyRequestMethod

	// ContextKeyRequestID is populated in the context by PopulateRequestContext
	ContextKeyRequestID
)

Variables

View Source
var ErrParsingRequestID = errors.New("Unknown value for RequestID")

ErrParsingRequestID is used when request id cannot be parsed

Functions

func DefaultErrorEncoder

func DefaultErrorEncoder(ctx context.Context, err error, w http.ResponseWriter)

DefaultErrorEncoder writes the error to the ResponseWriter, as a json-rpc error response, with an InternalError status code. The Error() string of the error will be used as the response error message. If the error implements ErrorCoder, the provided code will be set on the response error. If the error implements Headerer, the given headers will be set.

func ErrorMessage

func ErrorMessage(code int) string

ErrorMessage returns a message for the JSON RPC error code. It returns the empty string if the code is unknown.

func PopulateRequestContext

func PopulateRequestContext(ctx context.Context, r *Request) context.Context

PopulateRequestContext is a RequestFunc that populates several values into the context from the JSONRPC request. Those values may be extracted using the corresponding ContextKey type in this package.

Types

type DecodeRequestFunc

type DecodeRequestFunc func(context.Context, json.RawMessage) (request interface{}, err error)

DecodeRequestFunc extracts a user-domain request object from params.

type EncodeResponseFunc

type EncodeResponseFunc func(context.Context, interface{}) (response json.RawMessage, err error)

EncodeResponseFunc encodes the passed response object

type Error

type Error struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

Error defines a JSON RPC error that can be returned in a Response from the spec http://www.jsonrpc.org/specification#error_object

func NewError

func NewError(code int, message ...string) Error

NewError returns Error struct

func NewInvalidParamsError

func NewInvalidParamsError(msg ...string) Error

NewInvalidParamsError is helper for returning InvalidParamsError

func (Error) Error

func (e Error) Error() string

Error implements Errorer and error

func (Error) ErrorCode

func (e Error) ErrorCode() int

ErrorCode implements Errorer

type ErrorCoder

type ErrorCoder interface {
	ErrorCode() int
}

ErrorCoder is checked by DefaultErrorEncoder. If an error value implements ErrorCoder, the Error will be used when encoding the error. By default, InternalError (-32603) is used.

type Errorer

type Errorer interface {
	Error() string
	ErrorCoder
}

Errorer describes methods for managing errors

type Handler

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

Handler implements Handlerer interface

func NewHandler

func NewHandler(
	e endpoint.Endpoint,
	dec DecodeRequestFunc,
	enc EncodeResponseFunc,
	options ...HandlerOption,
) *Handler

NewHandler constructs a new handler, which implements jsonrcp.Handlerer and wraps the provided endpoint.

func (Handler) ServeJSONRPC

func (s Handler) ServeJSONRPC(ctx context.Context, requestHeader http.Header, params json.RawMessage) (responseParams json.RawMessage, responseHeader http.Header, err error)

ServeJSONRPC implements Handlerer

type HandlerOption

type HandlerOption func(*Handler)

HandlerOption sets an optional parameter for servers.

func HandlerAfter

func HandlerAfter(after ...HandlerResponseFunc) HandlerOption

HandlerAfter functions are executed on the response after the endpoint is invoked, but before anything is written to the client.

func HandlerBefore

func HandlerBefore(before ...HandlerRequestFunc) HandlerOption

HandlerBefore functions are executed on the request object

func HandlerErrorLogger

func HandlerErrorLogger(logger log.Logger) HandlerOption

HandlerErrorLogger is used to log non-terminal errors. By default, no errors are logged. This is intended as a diagnostic measure. Finer-grained control of error handling, including logging in more detail, should be performed in a custom ServerErrorEncoder or ServerFinalizer, both of which have access to the context.

type HandlerRequestFunc

type HandlerRequestFunc func(context.Context, http.Header) context.Context

HandlerRequestFunc may take information from an header and put it into a request context.

type HandlerResponseFunc

type HandlerResponseFunc func(context.Context, http.Header) context.Context

HandlerResponseFunc may take information from a request context and use it to add to response header

type Handlerer

type Handlerer interface {
	ServeJSONRPC(ctx context.Context, requestHeader http.Header, params json.RawMessage) (response json.RawMessage, responseHeader http.Header, err error)
}

Handlerer is the interface that provides method for serving JSON-RPC

type Handlers

type Handlers map[string]Handlerer

Handlers maps the method to the proper handler

func (Handlers) Set

func (h Handlers) Set(method string, handler Handlerer)

Set handler for given method, panics if method already exists

type Headerer

type Headerer interface {
	Headers() http.Header
}

Headerer is checked by DefaultErrorEncoder. If an error value implements Headerer, the provided headers will be applied to the response writer, after the Content-Type is set.

type NotificationResponse

type NotificationResponse struct{}

NotificationResponse defines a JSON RPC notification response

func (NotificationResponse) StatusCode

func (NotificationResponse) StatusCode() int

StatusCode returns no content status code

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params"`
	ID      *RequestID      `json:"id"`
}

Request defines a JSON RPC request from the spec http://www.jsonrpc.org/specification#request_object

func (*Request) Validate

func (r *Request) Validate() error

Validate request

type RequestID

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

RequestID defines a request ID that can be string, number, or null. An identifier established by the Client that MUST contain a String, Number, or NULL value if included. If it is not included it is assumed to be a notification. The value SHOULD normally not be Null and Numbers SHOULD NOT contain fractional parts.

func (*RequestID) Error

func (id *RequestID) Error() string

Error implements errors interface

func (*RequestID) Float32

func (id *RequestID) Float32() (float32, error)

Float32 returns the ID as a float value. An error is returned if the ID can't be treated as an float.

func (*RequestID) Int

func (id *RequestID) Int() (int, error)

Int returns the ID as an integer value. An error is returned if the ID can't be treated as an int.

func (*RequestID) MarshalJSON

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

MarshalJSON implements json.Marshaler

func (*RequestID) String

func (id *RequestID) String() (string, error)

String returns the ID as a string value. An error is returned if the ID can't be treated as an string.

func (*RequestID) UnmarshalJSON

func (id *RequestID) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler

type Response

type Response struct {
	JSONRPC     string      `json:"jsonrpc"`
	Result      interface{} `json:"result,omitempty"`
	Error       *Error      `json:"error,omitempty"`
	ID          *RequestID  `json:"id,omitempty"`
	RespHeaders http.Header `json:"-"`
}

Response defines a JSON RPC response from the spec http://www.jsonrpc.org/specification#response_object

func (Response) Headers

func (r Response) Headers() http.Header

Headers returns response headers

type Server

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

Server wraps an list of handlers and implements http.Handler

func NewServer

func NewServer(
	sh Handlers,
	options ...ServerOption,
) *Server

NewServer constructs a new Server, which implements http.Handler

func (Server) ServeHTTP

func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

type ServerOption

type ServerOption func(*Server)

ServerOption sets an optional parameter for servers

func ServerErrorEncoder

func ServerErrorEncoder(ee httptransport.ErrorEncoder) ServerOption

ServerErrorEncoder is used to encode errors to the http.ResponseWriter whenever they're encountered in the processing of a request. Clients can use this to provide custom error formatting and response codes. By default, errors will be written with the DefaultErrorEncoder.

Jump to

Keyboard shortcuts

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