Help us shape the future of Go! Take the 2026 Go Developer Survey

jrpc2

package module
v1.0.18 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2020 License: MIT Imports: 15 Imported by: 0

README

Golang JSON-RPC 2.0 over HTTP/1.1 Service Library

This library implements JSON-RPC 2.0 over HTTP/1.1 service loosely following specification:

About:

s3rj1k/jrpc2 was originally based on Jared Patricks bitwurx/jrpc2, but has been completely rewritten.

Client:

client folder contains basic JSON-RPC-2.0 client implementation with auto-generated ID as UUIDv4 string.

Known limitations:
  • no support for batch requests
Installation:
go get github.com/s3rj1k/jrpc2
Examples:
Running Tests:

This library contains a set of API tests to verify specification compliance, at least it tries to be compliant.

go test ./... -v
Linter installation:
curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $GOPATH/bin v1.15.0
go get -u github.com/Quasilyte/go-consistent
Run linters:
golangci-lint run
go-consistent -v ./...

Documentation

Index

Constants

View Source
const (
	ParseErrorCode     int = -32700
	InvalidRequestCode int = -32600
	MethodNotFoundCode int = -32601
	InvalidParamsCode  int = -32602
	InternalErrorCode  int = -32603
	NotImplementedCode int = -32000
	InvalidIDCode      int = -32001
	InvalidMethodCode  int = -32002
)

Error codes.

View Source
const (
	ParseErrorMessage     string = "Parse error"
	InvalidRequestMessage string = "Invalid Request"
	MethodNotFoundMessage string = "Method not found"
	InvalidParamsMessage  string = "Invalid params"
	InternalErrorMessage  string = "Internal error"
	NotImplementedMessage string = "Not implemented"
	InvalidIDMessage      string = "Invalid ID"
	InvalidMethodMessage  string = "Invalid method"
)

Error message.

View Source
const DefaultUnixSocketMode = 0777

DefaultUnixSocketMode specifies default permissions for unix socket.

View Source
const JSONRPCVersion string = "2.0"

JSONRPCVersion specifies the version of the JSON-RPC protocol.

Variables

This section is empty.

Functions

func GetClientAddressFromHeader added in v1.0.4

func GetClientAddressFromHeader(r *http.Request) net.IP

GetClientAddressFromHeader attempts to acquire Real Client IP (X-Real-IP, X-Client-IP) from upstream reverse proxy.

func GetClientAddressFromRequest added in v1.0.4

func GetClientAddressFromRequest(r *http.Request) net.IP

GetClientAddressFromRequest attempts to acquire Real Client IP from HTTP request.

func GetRealHostAddress

func GetRealHostAddress(r *http.Request) string

GetRealHostAddress attempts to acquire original HOST from upstream reverse proxy.

func GetRemoteAddress added in v1.0.6

func GetRemoteAddress(r *http.Request) string

GetRemoteAddress returns remote address (IP) of request source.

Types

type ErrorObject

type ErrorObject struct {
	// Code indicates the error type that occurred
	Code int `json:"code"`
	// Message provides a short description of the error
	Message string `json:"message"`
	// Data can contain additional information about the error
	Data interface{} `json:"data,omitempty"`
}

ErrorObject represents a response error object.

func ConvertIDtoString

func ConvertIDtoString(id *json.RawMessage) (string, *ErrorObject)

ConvertIDtoString converts ID parameter to string, also validates ID data type.

func GetPositionalFloat64Params

func GetPositionalFloat64Params(data ParametersObject) ([]float64, *ErrorObject)

GetPositionalFloat64Params parses positional param member of JSON-RPC 2.0 request that is know to contain float64 array.

func GetPositionalInt64Params

func GetPositionalInt64Params(data ParametersObject) ([]int64, *ErrorObject)

GetPositionalInt64Params parses positional param member of JSON-RPC 2.0 request that is know to contain int64 array.

func GetPositionalIntParams

func GetPositionalIntParams(data ParametersObject) ([]int, *ErrorObject)

GetPositionalIntParams parses positional param member of JSON-RPC 2.0 request that is know to contain int array.

func GetPositionalStringParams

func GetPositionalStringParams(data ParametersObject) ([]string, *ErrorObject)

GetPositionalStringParams parses positional param member of JSON-RPC 2.0 request that is know to contain string array.

func GetPositionalUint64Params

func GetPositionalUint64Params(data ParametersObject) ([]uint64, *ErrorObject)

GetPositionalUint64Params parses positional param member of JSON-RPC 2.0 request that is know to contain int64 array.

func GetPositionalUintParams

func GetPositionalUintParams(data ParametersObject) ([]uint, *ErrorObject)

GetPositionalUintParams parses positional param member of JSON-RPC 2.0 request that is know to contain uint array.

type HookError added in v1.0.1

type HookError struct {
	ErrorMsg string
	HTTPCode int
}

HookError custom error for Request/Response hook.

func NewHookError added in v1.0.3

func NewHookError(msg string, code int) *HookError

NewHookError creates new hook function error.

func (*HookError) Error added in v1.0.1

func (e *HookError) Error() string

Error defines method to satisfy default error interface.

type ParametersObject

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

ParametersObject represents input data for JSON-RPC 2.0 method.

func (ParametersObject) GetBasicAuth

func (p ParametersObject) GetBasicAuth() (username, password string, ok bool)

GetBasicAuth returns returns the username and password provided in the request's Authorization header.

func (ParametersObject) GetContentLength

func (p ParametersObject) GetContentLength() int64

GetContentLength returns the HTTP request content length.

func (ParametersObject) GetCookies

func (p ParametersObject) GetCookies() []*http.Cookie

GetCookies parses and returns the HTTP cookies sent with the request.

func (ParametersObject) GetHeaders

func (p ParametersObject) GetHeaders() http.Header

GetHeaders returns headers of the HTTP request.

func (ParametersObject) GetHost

func (p ParametersObject) GetHost() string

GetHost returns the HTTP server host.

func (ParametersObject) GetID

func (p ParametersObject) GetID() string

GetID returns request ID as string data type.

func (ParametersObject) GetMethod

func (p ParametersObject) GetMethod() string

GetMethod returns the HTTP request method.

func (ParametersObject) GetMethodName

func (p ParametersObject) GetMethodName() string

GetMethodName returns invoked request Method name as string data type.

func (ParametersObject) GetProto

func (p ParametersObject) GetProto() string

GetProto returns the HTTP protocol version.

func (ParametersObject) GetProtoMajor

func (p ParametersObject) GetProtoMajor() int

GetProtoMajor returns the HTTP protocol version, major part.

func (ParametersObject) GetProtoMinor

func (p ParametersObject) GetProtoMinor() int

GetProtoMinor returns the HTTP protocol version, minor part.

func (ParametersObject) GetRawID

func (p ParametersObject) GetRawID() *json.RawMessage

GetRawID returns request ID as json.RawMessage data type.

func (ParametersObject) GetRawJSONParams

func (p ParametersObject) GetRawJSONParams() json.RawMessage

GetRawJSONParams returns json.RawMessage of JSON-RPC 2.0 invoked method params data.

func (ParametersObject) GetReferer

func (p ParametersObject) GetReferer() string

GetReferer parses and returns the HTTP refere header sent with the request.

func (ParametersObject) GetRemoteAddress

func (p ParametersObject) GetRemoteAddress() string

GetRemoteAddress returns remote address of request source.

func (ParametersObject) GetRequestURI

func (p ParametersObject) GetRequestURI() string

GetRequestURI returns the HTTP protocol request URI.

func (ParametersObject) GetTrailer

func (p ParametersObject) GetTrailer() http.Header

GetTrailer returns trailer headers of the HTTP request.

func (ParametersObject) GetTransferEncoding

func (p ParametersObject) GetTransferEncoding() []string

GetTransferEncoding parses and returns TransferEncoding headers from the HTTP request.

func (ParametersObject) GetUserAgent

func (p ParametersObject) GetUserAgent() string

GetUserAgent returns User Agent of client who made request.

type RequestObject

type RequestObject struct {
	// Jsonrpc specifies the version of the JSON-RPC protocol, equals to "2.0"
	Jsonrpc string `json:"jsonrpc"`
	// Method contains the name of the method to be invoked
	Method string `json:"method"`
	// Params holds Raw JSON parameter data to be used during the invocation of the method
	Params json.RawMessage `json:"params"`
	// ID is a unique identifier established by the client
	ID *json.RawMessage `json:"id,omitempty"`
}

RequestObject represents a request object.

type ResponseObject

type ResponseObject struct {
	// Jsonrpc specifies the version of the JSON-RPC protocol, equals to "2.0"
	Jsonrpc string `json:"jsonrpc"`
	// Error contains the error object if an error occurred while processing the request
	Error *ErrorObject `json:"error,omitempty"`
	// Result contains the result of the called method
	Result interface{} `json:"result,omitempty"`
	// ID contains the client established request id or null
	ID *json.RawMessage `json:"id,omitempty"`
	// contains filtered or unexported fields
}

ResponseObject represents a response object.

func DefaultResponseObject

func DefaultResponseObject() *ResponseObject

DefaultResponseObject initializes default response object.

func (*ResponseObject) Marshal

func (responseObject *ResponseObject) Marshal() []byte

Marshal create a bytes encoded representation of a single response object.

func (*ResponseObject) ValidateHTTPProtocolVersion

func (responseObject *ResponseObject) ValidateHTTPProtocolVersion(r *http.Request) bool

ValidateHTTPProtocolVersion validates HTTP protocol version.

func (*ResponseObject) ValidateHTTPRequestHeaders

func (responseObject *ResponseObject) ValidateHTTPRequestHeaders(r *http.Request) bool

ValidateHTTPRequestHeaders validates HTTP request headers.

func (*ResponseObject) ValidateHTTPRequestMethod

func (responseObject *ResponseObject) ValidateHTTPRequestMethod(r *http.Request) bool

ValidateHTTPRequestMethod validates HTTP request method.

func (*ResponseObject) ValidateJSONRPCVersionNumber

func (responseObject *ResponseObject) ValidateJSONRPCVersionNumber(r *http.Request, version string) bool

ValidateJSONRPCVersionNumber validates JSON-RPC 2.0 request version member.

type Service

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

Service represents a JSON-RPC 2.0 capable HTTP server.

func Create

func Create(socket string) *Service

Create defines a new service instance over Unix Socket.

func CreateOverTCPWithTLS added in v1.0.4

func CreateOverTCPWithTLS(address, route, key, cert string) *Service

CreateOverTCPWithTLS defines a new service instance over TCP with TLS (HTTPS).

func CreateProxy

func CreateProxy(socket string) *Service

CreateProxy defines a new proxy service over Unix Socket.

func CreateProxyOverTCPWithTLS added in v1.0.4

func CreateProxyOverTCPWithTLS(address, route, key, cert string) *Service

CreateProxyOverTCPWithTLS defines a new proxy service over TCP with TLS (HTTPS).

func (*Service) AddAuthorization added in v1.0.8

func (s *Service) AddAuthorization(username, password string, networks []string) error

AddAuthorization adds (enables) Basic Authorization from specified remote network. When at least one mapping exists, Basic Authorization is enabled, default action is Deny Access. Method call with username that already exists in mapping will overwrite existing entry. Сolon ':' is used as a delimiter, must not be in username or/and password. To generate hashed password record use (CPU intensive, use cost below 10): htpasswd -nbB username password

func (*Service) AddAuthorizationFromFile added in v1.0.10

func (s *Service) AddAuthorizationFromFile(path string) error

AddAuthorizationFromFile adds (enables) Basic Authorization from file at path. When at least one mapping exists, Basic Authorization is enabled, default action is Deny Access. Duplicate users in the file will not raise error - the latest entry will be added to the mapping. Сolon ':' is used as a delimiter, must not be in username or/and password. To generate hashed password record use (CPU intensive, use cost below 10): htpasswd -nbB username password

func (*Service) Call

func (s *Service) Call(name string, data ParametersObject) (interface{}, *ErrorObject)

Call invokes the named method with the provided parameters.

func (*Service) CheckAuthorization added in v1.0.2

func (s *Service) CheckAuthorization(r *http.Request) error

CheckAuthorization checks Basic Authorization then enabled by service configuration.

func (*Service) GetAddress added in v1.0.4

func (s *Service) GetAddress() string

GetAddress gets custom network address from service object.

func (*Service) GetBehindReverseProxyFlag added in v1.0.11

func (s *Service) GetBehindReverseProxyFlag() bool

GetBehindReverseProxyFlag gets behind reverse proxy flag from service object.

func (*Service) GetCertificateFilePath added in v1.0.4

func (s *Service) GetCertificateFilePath() string

GetCertificateFilePath gets path of Certificate file in service object.

func (*Service) GetCertificateKeyFilePath added in v1.0.4

func (s *Service) GetCertificateKeyFilePath() string

GetCertificateKeyFilePath gets path of Certificate Key file in service object.

func (*Service) GetHeaders added in v1.0.4

func (s *Service) GetHeaders() map[string]string

GetHeaders gets custom headers from service object.

func (*Service) GetRoute added in v1.0.4

func (s *Service) GetRoute() string

GetRoute gets custom route from service object.

func (*Service) GetSocket added in v1.0.4

func (s *Service) GetSocket() string

GetSocket gets custom unix socket from service object.

func (*Service) GetSocketPermissions added in v1.0.4

func (s *Service) GetSocketPermissions() uint32

GetSocketPermissions gets custom unix socket permissions in service object.

func (*Service) Lock added in v1.0.18

func (s *Service) Lock()

Lock locks Service.

func (*Service) Register

func (s *Service) Register(name string, f func(ParametersObject) (interface{}, *ErrorObject))

Register maps the provided method name to the given function for later method calls.

func (*Service) RegisterProxy

func (s *Service) RegisterProxy(f func(ParametersObject) (interface{}, *ErrorObject))

RegisterProxy maps the 'rpc.proxy' method name to the given function for later method calls.

func (*Service) ServeHTTP

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

ServeHTTP implements needed interface for HTTP library, handles incoming RPC client requests, generates responses.

func (*Service) SetAddress added in v1.0.4

func (s *Service) SetAddress(address string)

SetAddress sets custom network address in service object.

func (*Service) SetBehindReverseProxyFlag added in v1.0.11

func (s *Service) SetBehindReverseProxyFlag(flag bool)

SetBehindReverseProxyFlag sets behind reverse proxy flag in service object.

func (*Service) SetCertificateFilePath added in v1.0.4

func (s *Service) SetCertificateFilePath(path string)

SetCertificateFilePath sets path to Certificate file in service object.

func (*Service) SetCertificateKeyFilePath added in v1.0.4

func (s *Service) SetCertificateKeyFilePath(path string)

SetCertificateKeyFilePath sets path to Certificate Key file in service object.

func (*Service) SetHeaders

func (s *Service) SetHeaders(headers map[string]string)

SetHeaders sets custom headers in service object.

func (*Service) SetRequestHookFunction

func (s *Service) SetRequestHookFunction(f func(r *http.Request, data []byte) error)

SetRequestHookFunction defines function that will be used as request hook.

func (*Service) SetResponseHookFunction

func (s *Service) SetResponseHookFunction(f func(r *http.Request, data []byte) error)

SetResponseHookFunction defines function that will be used as request hook.

func (*Service) SetRoute

func (s *Service) SetRoute(route string)

SetRoute sets custom route in service object.

func (*Service) SetSocket

func (s *Service) SetSocket(socket string)

SetSocket sets custom unix socket in service object.

func (*Service) SetSocketPermissions

func (s *Service) SetSocketPermissions(mode uint32)

SetSocketPermissions sets custom unix socket permissions in service object.

func (*Service) Start

func (s *Service) Start() error

Start binds the RPCHandler to the server route and starts the HTTP server over Unix Socket.

func (*Service) StartTCPTLS added in v1.0.4

func (s *Service) StartTCPTLS() error

StartTCPTLS binds the RPCHandler to the server route and starts the HTTP server over TCP.

func (*Service) Unlock added in v1.0.18

func (s *Service) Unlock()

Unlock unlocks Service.

func (*Service) WriteResponse added in v1.0.18

func (s *Service) WriteResponse(w http.ResponseWriter, respObj *ResponseObject)

WriteResponse writes JSON-RPC 2.0 response object to HTTP response writer.

Directories

Path Synopsis
client module

Jump to

Keyboard shortcuts

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