jrpc: github.com/twiglab/jrpc Index | Files

package jrpc

import "github.com/twiglab/jrpc"

Index

Package Files

client.go context.go debug.go error.go handler.go jsonrpc.go method.go schema.go unmarshal.go util.go

Constants

const (
    // Version is JSON-RPC 2.0.
    Version = "2.0"
)

Variables

var SchemaVersion = "http://json-schema.org/draft-04/schema#"

SchemaVersion is the JSON Schema version. If extending JSON Schema with custom values use a custom URI. RFC draft-wright-json-schema-00, section 6

func Params Uses

func Params(params ...interface{}) interface{}

Params is a helper function that uses the same parameter syntax as Call(). But you should consider to always use NewRequest() instead.

e.g. to manually create an RPCRequest object: request := &RPCRequest{

Method: "myMethod",
Params: Params("Alex", 35, true),

}

same with new request: request := NewRequest("myMethod", "Alex", 35, true)

If you know what you are doing you can omit the Params() call but potentially create incorrect rpc requests: request := &RPCRequest{

Method: "myMethod",
Params: 2, <-- invalid since a single primitive value must be wrapped in an array --> no magic without Params()

}

correct: request := &RPCRequest{

Method: "myMethod",
Params: []int{2}, <-- invalid since a single primitive value must be wrapped in an array

}

func ParseRequest Uses

func ParseRequest(r *http.Request) ([]*Request, bool, *Error)

ParseRequest parses a HTTP request to JSON-RPC request.

func RequestID Uses

func RequestID(c context.Context) *json.RawMessage

RequestID takes request id from context.

func SendResponse Uses

func SendResponse(w http.ResponseWriter, resp []*Response, batch bool) error

SendResponse writes JSON-RPC response.

func WithRequestID Uses

func WithRequestID(c context.Context, id *json.RawMessage) context.Context

WithRequestID adds request id to context.

type DebugHandler Uses

type DebugHandler struct {
    *MethodRepository
}

func Debug Uses

func Debug(mr *MethodRepository) *DebugHandler

func (*DebugHandler) ServeHTTP Uses

func (d *DebugHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Definitions Uses

type Definitions map[string]*Type

Definitions hold schema definitions. http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.26 RFC draft-wright-json-schema-validation-00, section 5.26

type Echo Uses

type Echo struct {
}

func NewEcho Uses

func NewEcho() *Echo

func (*Echo) Name Uses

func (e *Echo) Name() string

func (*Echo) Params Uses

func (e *Echo) Params() interface{}

func (*Echo) Result Uses

func (e *Echo) Result() interface{}

func (*Echo) ServeJSONRPC Uses

func (h *Echo) ServeJSONRPC(c context.Context, params *json.RawMessage) (interface{}, *Error)

type EchoParams Uses

type EchoParams struct {
    Name string `json:"name"`
}

type EchoResult Uses

type EchoResult struct {
    Message string `json:"message"`
}

type Error Uses

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

An Error is a wrapper for a JSON interface value.

func ErrInternal Uses

func ErrInternal() *Error

ErrInternal returns internal error.

func ErrInvalidParams Uses

func ErrInvalidParams() *Error

ErrInvalidParams returns invalid params error.

func ErrInvalidRequest Uses

func ErrInvalidRequest() *Error

ErrInvalidRequest returns invalid request error.

func ErrMethodNotFound Uses

func ErrMethodNotFound() *Error

ErrMethodNotFound returns method not found error.

func ErrParse Uses

func ErrParse() *Error

ErrParse returns parse error.

func Unmarshal Uses

func Unmarshal(params *json.RawMessage, dst interface{}) *Error

Unmarshal decodes JSON-RPC params.

func (*Error) Error Uses

func (e *Error) Error() string

Error implements error interface.

type ErrorCode Uses

type ErrorCode int

A ErrorCode by JSON-RPC 2.0.

const (
    // ErrorCodeParse is parse error code.
    ErrorCodeParse ErrorCode = -32700
    // ErrorCodeInvalidRequest is invalid request error code.
    ErrorCodeInvalidRequest ErrorCode = -32600
    // ErrorCodeMethodNotFound is method not found error code.
    ErrorCodeMethodNotFound ErrorCode = -32601
    // ErrorCodeInvalidParams is invalid params error code.
    ErrorCodeInvalidParams ErrorCode = -32602
    // ErrorCodeInternal is internal error code.
    ErrorCodeInternal ErrorCode = -32603
)

type ExHandler Uses

type ExHandler interface {
    Handler
    Name() string
    Params() interface{}
    Result() interface{}
}

type HTTPError Uses

type HTTPError struct {
    Code int
    // contains filtered or unexported fields
}

HTTPError represents a error that occurred on HTTP level.

An error of type HTTPError is returned when a HTTP error occurred (status code) and the body could not be parsed to a valid RPCResponse object that holds a RPCError.

Otherwise a RPCResponse object is returned with a RPCError field that is not nil.

func (*HTTPError) Error Uses

func (e *HTTPError) Error() string

Error function is provided to be used as error object.

type Handler Uses

type Handler interface {
    ServeJSONRPC(c context.Context, params *json.RawMessage) (result interface{}, err *Error)
}

type HanlerFunc Uses

type HanlerFunc func(context.Context, *json.RawMessage) (result interface{}, err *Error)

func (HanlerFunc) ServeJSONRPC Uses

func (h HanlerFunc) ServeJSONRPC(c context.Context, params *json.RawMessage) (result interface{}, err *Error)

type Metadata Uses

type Metadata struct {
    Handler Handler
    Params  interface{}
    Result  interface{}
}

type MethodReference Uses

type MethodReference struct {
    Name    string  `json:"name"`
    Handler string  `json:"handler"`
    Params  *Schema `json:"params,omitempty"`
    Result  *Schema `json:"result,omitempty"`
}

A MethodReference is a reference of JSON-RPC method.

type MethodRepository Uses

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

func NewMethodRepository Uses

func NewMethodRepository() *MethodRepository

NewMethodRepository returns new MethodRepository.

func (*MethodRepository) InvokeMethod Uses

func (mr *MethodRepository) InvokeMethod(c context.Context, r *Request) *Response

InvokeMethod invokes JSON-RPC method.

func (*MethodRepository) Methods Uses

func (mr *MethodRepository) Methods() map[string]Metadata

Methods returns registered methods.

func (*MethodRepository) RegisterExHandler Uses

func (mr *MethodRepository) RegisterExHandler(h ExHandler)

func (*MethodRepository) RegisterHandler Uses

func (mr *MethodRepository) RegisterHandler(method string, h Handler, params, result interface{})

func (*MethodRepository) ServeDebug Uses

func (mr *MethodRepository) ServeDebug(w http.ResponseWriter, r *http.Request)

ServeDebug views registered method list.

func (*MethodRepository) ServeHTTP Uses

func (mr *MethodRepository) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*MethodRepository) TakeHandler Uses

func (mr *MethodRepository) TakeHandler(r *Request) (Handler, *Error)

TakeHandler takes jsonrpc.Func in MethodRepository.

type RPCClient Uses

type RPCClient interface {
    // Call is used to send a JSON-RPC request to the server endpoint.
    //
    // The spec states, that params can only be an array or an object, no primitive values.
    // So there are a few simple rules to notice:
    //
    // 1. no params: params field is omitted. e.g. Call("getinfo")
    //
    // 2. single params primitive value: value is wrapped in array. e.g. Call("getByID", 1423)
    //
    // 3. single params value array or object: value is unchanged. e.g. Call("storePerson", &Person{Name: "Alex"})
    //
    // 4. multiple params values: always wrapped in array. e.g. Call("setDetails", "Alex, 35, "Germany", true)
    //
    // Examples:
    //   Call("getinfo") -> {"method": "getinfo"}
    //   Call("getPersonId", 123) -> {"method": "getPersonId", "params": [123]}
    //   Call("setName", "Alex") -> {"method": "setName", "params": ["Alex"]}
    //   Call("setMale", true) -> {"method": "setMale", "params": [true]}
    //   Call("setNumbers", []int{1, 2, 3}) -> {"method": "setNumbers", "params": [1, 2, 3]}
    //   Call("setNumbers", 1, 2, 3) -> {"method": "setNumbers", "params": [1, 2, 3]}
    //   Call("savePerson", &Person{Name: "Alex", Age: 35}) -> {"method": "savePerson", "params": {"name": "Alex", "age": 35}}
    //   Call("setPersonDetails", "Alex", 35, "Germany") -> {"method": "setPersonDetails", "params": ["Alex", 35, "Germany"}}
    //
    // for more information, see the examples or the unit tests
    Call(method string, params ...interface{}) (*RPCResponse, error)

    // CallRaw is like Call() but without magic in the requests.Params field.
    // The RPCRequest object is sent exactly as you provide it.
    // See docs: NewRequest, RPCRequest, Params()
    //
    // It is recommended to first consider Call() and CallFor()
    CallRaw(request *RPCRequest) (*RPCResponse, error)

    // CallFor is a very handy function to send a JSON-RPC request to the server endpoint
    // and directly specify an object to store the response.
    //
    // out: will store the unmarshaled object, if request was successful.
    // should always be provided by references. can be nil even on success.
    // the behaviour is the same as expected from json.Unmarshal()
    //
    // method and params: see Call() function
    //
    // if the request was not successful (network, http error) or the rpc response returns an error,
    // an error is returned. if it was an JSON-RPC error it can be casted
    // to *RPCError.
    //
    CallFor(out interface{}, method string, params ...interface{}) error

    // CallBatch invokes a list of RPCRequests in a single batch request.
    //
    // Most convenient is to use the following form:
    // CallBatch(RPCRequests{
    //   NewRequest("myMethod1", 1, 2, 3),
    //   NewRequest("myMethod2", "Test"),
    // })
    //
    // You can create the []*RPCRequest array yourself, but it is not recommended and you should notice the following:
    // - field Params is sent as provided, so Params: 2 forms an invalid json (correct would be Params: []int{2})
    // - you can use the helper function Params(1, 2, 3) to use the same format as in Call()
    // - field JSONRPC is overwritten and set to value: "2.0"
    // - field ID is overwritten and set incrementally and maps to the array position (e.g. requests[5].ID == 5)
    //
    //
    // Returns RPCResponses that is of type []*RPCResponse
    // - note that a list of RPCResponses can be received unordered so it can happen that: responses[i] != responses[i].ID
    // - RPCPersponses is enriched with helper functions e.g.: responses.HasError() returns  true if one of the responses holds an RPCError
    CallBatch(requests RPCRequests) (RPCResponses, error)

    // CallBatchRaw invokes a list of RPCRequests in a single batch request.
    // It sends the RPCRequests parameter is it passed (no magic, no id autoincrement).
    //
    // Consider to use CallBatch() instead except you have some good reason not to.
    //
    // CallBatchRaw(RPCRequests{
    //   &RPCRequest{
    //     ID: 123,            // this won't be replaced in CallBatchRaw
    //     JSONRPC: "wrong",   // this won't be replaced in CallBatchRaw
    //     Method: "myMethod1",
    //     Params: []int{1},   // there is no magic, be sure to only use array or object
    //   },
    //   &RPCRequest{
    //     ID: 612,
    //     JSONRPC: "2.0",
    //     Method: "myMethod2",
    //     Params: Params("Alex", 35, true), // you can use helper function Params() (see doc)
    //   },
    // })
    //
    // Returns RPCResponses that is of type []*RPCResponse
    // - note that a list of RPCResponses can be received unordered
    // - the id's must be mapped against the id's you provided
    // - RPCPersponses is enriched with helper functions e.g.: responses.HasError() returns  true if one of the responses holds an RPCError
    CallBatchRaw(requests RPCRequests) (RPCResponses, error)
}

RPCClient sends JSON-RPC requests over HTTP to the provided JSON-RPC backend.

RPCClient is created using the factory function NewClient().

func NewClient Uses

func NewClient(endpoint string) RPCClient

NewClient returns a new RPCClient instance with default configuration.

endpoint: JSON-RPC service URL to which JSON-RPC requests are sent.

func NewClientWithOpts Uses

func NewClientWithOpts(endpoint string, opts *RPCClientOpts) RPCClient

NewClientWithOpts returns a new RPCClient instance with custom configuration.

endpoint: JSON-RPC service URL to which JSON-RPC requests are sent.

opts: RPCClientOpts provide custom configuration

type RPCClientOpts Uses

type RPCClientOpts struct {
    HTTPClient    *http.Client
    CustomHeaders map[string]string
}

RPCClientOpts can be provided to NewClientWithOpts() to change configuration of RPCClient.

HTTPClient: provide a custom http.Client (e.g. to set a proxy, or tls options)

CustomHeaders: provide custom headers, e.g. to set BasicAuth

type RPCError Uses

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

RPCError represents a JSON-RPC error object if an RPC error occurred.

Code: holds the error code

Message: holds a short error message

Data: holds additional error data, may be nil

See: http://www.jsonrpc.org/specification#error_object

func (*RPCError) Error Uses

func (e *RPCError) Error() string

Error function is provided to be used as error object.

type RPCRequest Uses

type RPCRequest struct {
    Method  string      `json:"method"`
    Params  interface{} `json:"params,omitempty"`
    ID      int         `json:"id"`
    JSONRPC string      `json:"jsonrpc"`
}

RPCRequest represents a JSON-RPC request object.

Method: string containing the method to be invoked

Params: can be nil. if not must be an json array or object

ID: may always set to 1 for single requests. Should be unique for every request in one batch request.

JSONRPC: must always be set to "2.0" for JSON-RPC version 2.0

See: http://www.jsonrpc.org/specification#request_object

Most of the time you shouldn't create the RPCRequest object yourself. The following functions do that for you: Call(), CallFor(), NewRequest()

If you want to create it yourself (e.g. in batch or CallRaw()), consider using Params(). Params() is a helper function that uses the same parameter syntax as Call().

e.g. to manually create an RPCRequest object: request := &RPCRequest{

Method: "myMethod",
Params: Params("Alex", 35, true),

}

If you know what you are doing you can omit the Params() call to avoid some reflection but potentially create incorrect rpc requests: request := &RPCRequest{

Method: "myMethod",
Params: 2, <-- invalid since a single primitive value must be wrapped in an array --> no magic without Params()

}

correct: request := &RPCRequest{

Method: "myMethod",
Params: []int{2}, <-- invalid since a single primitive value must be wrapped in an array

}

func NewRequest Uses

func NewRequest(method string, params ...interface{}) *RPCRequest

NewRequest returns a new RPCRequest that can be created using the same convenient parameter syntax as Call()

e.g. NewRequest("myMethod", "Alex", 35, true)

type RPCRequests Uses

type RPCRequests []*RPCRequest

RPCRequests is of type []*RPCRequest. This type is used to provide helper functions on the request list

type RPCResponse Uses

type RPCResponse struct {
    JSONRPC string      `json:"jsonrpc"`
    Result  interface{} `json:"result,omitempty"`
    Error   *RPCError   `json:"error,omitempty"`
    ID      int         `json:"id"`
}

RPCResponse represents a JSON-RPC response object.

Result: holds the result of the rpc call if no error occurred, nil otherwise. can be nil even on success.

Error: holds an RPCError object if an error occurred. must be nil on success.

ID: may always be 0 for single requests. is unique for each request in a batch call (see CallBatch())

JSONRPC: must always be set to "2.0" for JSON-RPC version 2.0

See: http://www.jsonrpc.org/specification#response_object

func (*RPCResponse) GetBool Uses

func (RPCResponse *RPCResponse) GetBool() (bool, error)

GetBool converts the rpc response to a bool and returns it.

If result was not a bool an error is returned.

func (*RPCResponse) GetFloat Uses

func (RPCResponse *RPCResponse) GetFloat() (float64, error)

GetFloat converts the rpc response to float64 and returns it.

If result was not an float64 an error is returned.

func (*RPCResponse) GetInt Uses

func (RPCResponse *RPCResponse) GetInt() (int64, error)

GetInt converts the rpc response to an int64 and returns it.

If result was not an integer an error is returned.

func (*RPCResponse) GetObject Uses

func (RPCResponse *RPCResponse) GetObject(toType interface{}) error

GetObject converts the rpc response to an arbitrary type.

The function works as you would expect it from json.Unmarshal()

func (*RPCResponse) GetString Uses

func (RPCResponse *RPCResponse) GetString() (string, error)

GetString converts the rpc response to a string and returns it.

If result was not a string an error is returned.

type RPCResponses Uses

type RPCResponses []*RPCResponse

RPCResponses is of type []*RPCResponse. This type is used to provide helper functions on the result list

func (RPCResponses) AsMap Uses

func (res RPCResponses) AsMap() map[int]*RPCResponse

AsMap returns the responses as map with response id as key.

func (RPCResponses) GetByID Uses

func (res RPCResponses) GetByID(id int) *RPCResponse

GetByID returns the response object of the given id, nil if it does not exist.

func (RPCResponses) HasError Uses

func (res RPCResponses) HasError() bool

HasError returns true if one of the response objects has Error field != nil

type Reflector Uses

type Reflector struct {
    // AllowAdditionalProperties will cause the Reflector to generate a schema
    // with additionalProperties to 'true' for all struct types. This means
    // the presence of additional keys in JSON objects will not cause validation
    // to fail. Note said additional keys will simply be dropped when the
    // validated JSON is unmarshaled.
    AllowAdditionalProperties bool

    // RequiredFromJSONSchemaTags will cause the Reflector to generate a schema
    // that requires any key tagged with `jsonschema:required`, overriding the
    // default of requiring any key *not* tagged with `json:,omitempty`.
    RequiredFromJSONSchemaTags bool

    // ExpandedStruct will cause the toplevel definitions of the schema not
    // be referenced itself to a definition.
    ExpandedStruct bool
}

A Reflector reflects values into a Schema.

func (*Reflector) Reflect Uses

func (r *Reflector) Reflect(v interface{}) *Schema

Reflect reflects to Schema from a value.

func (*Reflector) ReflectFromType Uses

func (r *Reflector) ReflectFromType(t reflect.Type) *Schema

ReflectFromType generates root schema

type Request Uses

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

A Request represents a JSON-RPC request received by the server.

type Response Uses

type Response struct {
    Version string           `json:"jsonrpc"`
    Result  interface{}      `json:"result,omitempty"`
    Error   *Error           `json:"error,omitempty"`
    ID      *json.RawMessage `json:"id,omitempty"`
}

A Response represents a JSON-RPC response returned by the server.

func NewResponse Uses

func NewResponse(r *Request) *Response

NewResponse generates a JSON-RPC response.

type Schema Uses

type Schema struct {
    *Type
    Definitions Definitions `json:"definitions,omitempty"`
}

Schema is the root schema. RFC draft-wright-json-schema-00, section 4.5

func Reflect Uses

func Reflect(v interface{}) *Schema

Reflect reflects to Schema from a value using the default Reflector

func ReflectFromType Uses

func ReflectFromType(t reflect.Type) *Schema

ReflectFromType generates root schema using the default Reflector

type Type Uses

type Type struct {
    // RFC draft-wright-json-schema-00
    Version string `json:"$schema,omitempty"` // section 6.1
    Ref     string `json:"$ref,omitempty"`    // section 7
    // RFC draft-wright-json-schema-validation-00, section 5
    MultipleOf           int              `json:"multipleOf,omitempty"`           // section 5.1
    Maximum              int              `json:"maximum,omitempty"`              // section 5.2
    ExclusiveMaximum     bool             `json:"exclusiveMaximum,omitempty"`     // section 5.3
    Minimum              int              `json:"minimum,omitempty"`              // section 5.4
    ExclusiveMinimum     bool             `json:"exclusiveMinimum,omitempty"`     // section 5.5
    MaxLength            int              `json:"maxLength,omitempty"`            // section 5.6
    MinLength            int              `json:"minLength,omitempty"`            // section 5.7
    Pattern              string           `json:"pattern,omitempty"`              // section 5.8
    AdditionalItems      *Type            `json:"additionalItems,omitempty"`      // section 5.9
    Items                *Type            `json:"items,omitempty"`                // section 5.9
    MaxItems             int              `json:"maxItems,omitempty"`             // section 5.10
    MinItems             int              `json:"minItems,omitempty"`             // section 5.11
    UniqueItems          bool             `json:"uniqueItems,omitempty"`          // section 5.12
    MaxProperties        int              `json:"maxProperties,omitempty"`        // section 5.13
    MinProperties        int              `json:"minProperties,omitempty"`        // section 5.14
    Required             []string         `json:"required,omitempty"`             // section 5.15
    Properties           map[string]*Type `json:"properties,omitempty"`           // section 5.16
    PatternProperties    map[string]*Type `json:"patternProperties,omitempty"`    // section 5.17
    AdditionalProperties json.RawMessage  `json:"additionalProperties,omitempty"` // section 5.18
    Dependencies         map[string]*Type `json:"dependencies,omitempty"`         // section 5.19
    Enum                 []interface{}    `json:"enum,omitempty"`                 // section 5.20
    Type                 string           `json:"type,omitempty"`                 // section 5.21
    AllOf                []*Type          `json:"allOf,omitempty"`                // section 5.22
    AnyOf                []*Type          `json:"anyOf,omitempty"`                // section 5.23
    OneOf                []*Type          `json:"oneOf,omitempty"`                // section 5.24
    Not                  *Type            `json:"not,omitempty"`                  // section 5.25
    Definitions          Definitions      `json:"definitions,omitempty"`          // section 5.26
    // RFC draft-wright-json-schema-validation-00, section 6, 7
    Title       string      `json:"title,omitempty"`       // section 6.1
    Description string      `json:"description,omitempty"` // section 6.1
    Default     interface{} `json:"default,omitempty"`     // section 6.2
    Format      string      `json:"format,omitempty"`      // section 7
    // RFC draft-wright-json-schema-hyperschema-00, section 4
    Media          *Type  `json:"media,omitempty"`          // section 4.3
    BinaryEncoding string `json:"binaryEncoding,omitempty"` // section 4.3
}

Type represents a JSON Schema object type.

Package jrpc imports 13 packages (graph). Updated 2019-03-05. Refresh now. Tools for package owners.